Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Considering all this chat about offline storage I may as well bring up a indexedDB/webSQL wrapper that I'm writing for an application I'm working on. I intend to make it 100% offline capable, plugging into an existing Django application I've made (http://spanner-pms.com) so I can make an all new front end.

The library is called JohoDB, find it here http://malucomarinero.bitbucket.org/johodb/

I've had really good experiences with it so far, integrating it into Angular cleanly. Still lots to do like data migration, generic relations and a bunch of other things, but I'm pretty happy with how its progressing, at least for my own use case.

Adbot
ADBOT LOVES YOU

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
I feel like I'm about ready to drink some serious koolaid here. I've been looking at https://reactjs.org, stumbled upon it while looking up AngularJS optimization notes after hitting some peformance issues on a project with AngularJS.

I absolutely love the ideas behind this framework. Functional programming, composable components, properly batched DOM updates rather than piecemeal binding, and a clear separation of immutable and mutable state.

Its a really clever approach and I'm keen as to give it a try in the near future. It helps that its running on Facebook so while it may not be widely adopted, its certainly seeing a lot of production usage.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

sim posted:

I'm also really interested in React, but haven't tried it on a real project. The thing that scares me is writing HTML inside of JS. But I can understand the benefits, and with every JS MVC there's already a lot of blurring between HTML/JS anyway. NetTuts just posted a nice intro to React: http://net.tutsplus.com/tutorials/javascript-ajax/intro-to-the-react-framework/

Yeah, this is the thing, my experience with AngularJS is that you'll be hopping between template, controller and directive structure for a single change in behaviour anyway. Angular expressions and directives ensure that you've got templates hard coupled to underlying scripting

On the other hand React encourages all of a components necessary pieces (aside from style) to be located in the one 'class', and that is going to be very powerful for creating reusable components that are well encapsulated. The fact that performance is considered of high priority pretty much seals the deal for me. I'll give a trip report once I've got some runs on the board for this new project I'm starting.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
As an aside, although I haven't ye tried it one of the cool parts about ReactJS's approach to component rendering is that it can (according to their brief experiments with Node) generate perfectly suitable server side markup through its rendering of components, as long as its fed the right data. So much so that a potential suggested use is to render the page server side so the DOM has been pregenerated, and then by the time the JavaScript loads client side all it would need to do is attach the appropriate handlers as per the component set, giving super fast setup times.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

excidium posted:

Hopefully this is the right place to ask AngularJS + PhoneGap questions. I created a pretty basic app locally that works perfectly in the browser. When I go to emulate it though my routes all stop working. I get file:///(route-name) Page load failed with error: The requested URL was not found on this server. So I get that it's most likely a cross origin request issue, but I don't know how to get around it yet. I have approximately 20 some-odd routes and 20 directives that all use templateUrl files to load my page data. I'm stuck on what to do to get this working.

Shouldn't you point phonegap to served content instead of a file? Then from there if you need to work offline add in Html5 offline caching of the static assets.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

excidium posted:

Well, this was a totally offline app, so my first thought was that the files would just work similar to how they do locally (but I guess that's with a web-server). I could technically re-do the thing so that it's not doing any templateUrl requests, but it seemed like it should just work anyway. I'll look at the HTML5 caching though, see if that works for me.

The Templateurl calls are fine if you serve from an endpoint rather than try to run it as a local file. Just use the cache manifest to specify that the browser will persist all the relevant resources, including the template URL files.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

excidium posted:

Is it not possible to download these files as part of the app package so that it doesn't have to access the internet at all? A pre-populated cache of sorts?

I'm unsure, this is where I leave off as I haven't got much experience with Phonegap itself. A preloaded appcache would be great if it's possible, otherwise a way for a phonegap to act as a local 'server' so were not trying to do direct file access which clamps down hard on browser permissions.

I'm assuming that you want to have an almost offline install right? Otherwise maybe there's a way to populate the appcache in the install process.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

excidium posted:

Well the idea was that the app itself could be used offline and downloaded/installed in one go from either the iTunes or Google Play store. I didn't want to learn native code in 2 languages to code what was a pretty simple app so I thought HTML/JS would be a good alternative with PhoneGap covering the device specific stuff around my code. I'm thinking that it might just be better to change my template calls to template: '<html goes here>' and prevent the need for most/all of the templateUrl: calls that are causing the issues to begin with.

If you can make that work, then go for it. I do believe Angular also has SCP (secure content policy) version that may help with getting it to work in this context. I know in using Angular for a Chrome Extension I needed to use secure content policy, maybe the rules apply in your sandboxed Phonegap environment too.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

fletcher posted:

Very interesting perspective Mr. Wynand, just wanted to say thanks for sharing your experience!

Yeah. To be honest that post is me about 2 months ago. We changed core functionality to React js and have not looked back since. We pulled page loads down from 35seconds in large data sets, down to 3 seconds, and ended up being able to easily augment components to start reusing DOM elements in an infinite scrolling setup, for even greater mobile efficiency gains.

I feel the same way about Google's support of open source as well. They lose interest rather than admit defeat, and they're not resolving core issues.

Our container is still angular at present, but the hard work is done by react, and that balance is only going to shift further away from Angular as time goes on.

As an aside, I've been doing some pure react work lately and really enjoying it. Couple it with some extra modules like director for page routing, and precompiled jade templates and you end up with this super maintainable structure that runs like lightning. Never going back to angular that's for sure. Its full of quick wins but hits it's limits far too early to maintain viability, and that's probably one of the key issues.

Back end frameworks that are slow, like Django and Ruby, can at least be scaled by throwing hardware at the problem, at least to a point. You don't have that option on the client side, especially if you're involving mobile, so the only sustainable option is something that's fast by default.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Urit posted:

So what's a good ORM or some kind of library to make the mapping between tabular data and ~magical objects~ easier? The reason Mongo is so easy to plug in is you literally just feed it JSON objects and it barfs JSON objects back, no translation required.

Also, what's the thread consensus on React.js? I kind of like it because it's basically like writing Razor syntax from C#-land (which is where I started coding).

I've been telling everyone who'll listen that it rocks. Fast and sensible model with well written documentation, that makes it really easy to reason about the state of your application.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Chenghiz posted:

dumb question re: React - I have a page with a big table handled by React that need to be filterable by column. Using React I have methods that listen for filter add/remove events via pub/sub, but I need to have a UI to control adding and removing filters. I want to put the controls for the filters in a pretty distinct page element from the table (a jquery mobile panel, to be specific), so I feel like it would be awkward to expand the scope of the React element to including basically the entire page (I'm using jQuery Mobile for layout and controls).

Can anyone offer some advice on how to handle this situation? This is my first time trying to implement React in production and nobody on my team has more experience than I do, but I do have a ton of experience with jquery mobile.

This is a good blog post to get into component thinking. Basically, the container is a component, and then you drill down to the smallest components, ideally those are reusable to the point the more granular they become, whether it's a widget or whatevs.
http://facebook.github.io/react/blog/2013/11/05/thinking-in-react.html

The key there is to figure out your hierarchy of state. This means establishing what needs to know what. In this instance likely your 'page' component handles the state, and then has sub components representing your filters and the table respectively. At that point, you give the filter component a link to pass state changes back up to the page component, and then that state works down to the table via properties.

Does that make sense?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
I'll make a big effort post about React component structure later if you like, including embedding inside other frameworks (I'm doing - in separate projects, embedding react in an angular structure, and react standalone, representing the entire application), just having family time right now.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
edit: lets try that with the right tags

Now, this is all just from a guy using it, and I may be wrong on some things when it comes to the RIGHT way, but this is all coming from my experience so hopefully it's valuable.

The React State
What React is and how it handles state is probably the most important thing to understand coming in. In React state flows down from the root component. When you use React.renderComponent you feed it some properties and then from there it should be able to render everything below it, whether that's just a self contained UI Component or your entire single page app.

So, properties and state are the way you represent the moving parts of your component. Properties are immutable, and state isn't. Usually state is passed down the component tree as properties, which basically means you use the state of one component as your source of truth, and let the sub components have that state through their properties. Where you put the state depends on what makes sense for your application.

Using the application example of Chengiz, it's clear that most of the state will need to be held in a component that encapsulates the table and the filtering widgets. From that point, you pass the filtering widgets what they need through properties, and also handler that allows them to pass state changes back up the hierarchy. That would be bound with onChange or something, depending on how you're implementing your widget.

A digression, implementing a jQuery widget
If you need to create a custom select (common case), you might be using another library that works on HTML Select elements. That's not a big deal, ideally you should be able to create a normal <select> (or whatever collection of DOM elements required by the UI library), and then apply the methods on the DOM node during a componentDidMount method, which is the point where you can access the actual DOM nodes. Provided your library isn't mutating the mounted DOM node, they should play nice, as the library UI updates the select, and then your onChange handlers on the select then communicate the state up the tree. If that fails, you can still access the methods in componentDidMount to get your library to directly talk to the state.

...back to React state
So you'd be passing information down to the widgets, those properties would likely be:
- arrays of choices
- onChange handler function, that will let the widget tell the root component about changes
- current values

If there was a little more complexity, say you had to press save to commit changes on the widget, then that widget would have it's own state, and the properties would contain initial values. When that initial value property updates you reset the state of the widget, but otherwise the widget can do it's own thing without being locked by the root component.

Displaying View Data
Usually the components that are displaying data, they should be just fed properties. What the data is. If you have controls outside that change how the data is presented, then you'd have that information as properties too, but otherwise it can be state on the display components. In the table example earlier, consider this setup:

pre:
- FilteringTableView (props: rawData)
  state: filters
  - FilterWidgets - (props: choicesFromData, onChangeHandler, filters)
  - DisplayTable - (props: filteredData)
    state: tableSortOrders
Here you've created the FilteringTableView, and fed it the rawData as a property. It initialises with a state of {filters: undefined}, and then there's enough information to render the rest of the tree from that data. When we create the DisplayTable component, it takes the data and turns it into a table. -- This could be any data provided you write code with enough generalisation, but that depends on the use case. -- With that table, if you wanted to make it so you could change the sorting of the table, there's no real need for it to communicate with the root component because changing the sort won't affect it, so you keep that state right there on the table.

If necessary you could take your components to an even more granular level with:

pre:
- DisplayTable
  - DisplayTableHeader
    - DisplayTableColumnHeader
  - DisplayTableBody
    - DisplayTableRow
      - DisplayTableCell
...but that really depends on how complicated your application is. If it's just dumb <tr> and <td> elements you probably won't bother with that.


Implications of React's State Model
Now to answer your question ShaunO, React doesn't really have a concept of two way data binding out of the box, so the paradigm of observables doesn't really exist. What you have instead is a system that renders quickly, binds event handlers and then just sits there. As in, it's not running timers, watchers on variables, nothing. All it's doing is waiting for you to trigger some change in the system and then react to it (hence the name). If you want to have two way data binding, you take a DOM element and give it a handler that updates the state, and that's pretty much it.

From React's docs: http://facebook.github.io/react/docs/forms.html
JavaScript code:
  getInitialState: function() {
    return {value: 'Hello!'};
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    var value = this.state.value;
    return <input type="text" value={value} onChange={this.handleChange} />;
  }
So you can see here, the two way bind is expressed by having the state be represented by the <input>'s value, but then any changes get fed back to a handler that runs setState. It's not particularly hard to create a pattern that generalises this relationship either, and you have an addon made for React here: http://facebook.github.io/react/docs/two-way-binding-helpers.html , that said I'm playing with a generalisation for one project that'll be a little nicer for deep complex forms that have many nested components, rather than passing a million props down the line.

There's a lot of ways to approach passing state to where it's needed, in one project I have a fairly complex page with lots of interactions that cascade throughout. In that case I'm using a controller object that essentially helps everything communicate actions which then get sent to the root component to trigger a rerender. The key thing is though, if you're limiting duplication of state by using properties, you're making it easy to keep the entire UI in sync because the state only exists where it makes sense to exist.

React can do this very quickly too, because it does all the hard work in pure Javascript, and only talks to the DOM in one big optimised operation. Once it has rendered, the app is at rest, it doesn't need to keep watching, running timers or whatever because all it needs to know is when setState or setProps is called to start another render cycle. You can even get more performance out of it by using a shouldComponentUpdate function, which allows you to take the incoming props & state, compare them to the existing props & state, and decide whether or not a render is needed. In the right places that can mean React can skip huge swathes of the DOM on it's render passes.

React and Arrays
React keeps track of DOM elements and how they link to React Components via a html attribute, data-reactid. There's no other proprietary tags in use which is great for a semantic HTML output. Usually React automatically figures out the id based on a random one for the root, followed by a numeric sequence for every component inside. In the case of rendered arrays however it's recommended you use keys. Basically, that just means when you render an array of components, you give them a key, and that way React can know how to reuse those DOM elements when the Array gets reordered, rather than rendering the changes in a less efficient manner.

You can do some really cool things with this that are much more annoying to reason about with Angular (in my experience with that), such as an infinite scrolling view that simply reuses all the DOM elements, cycling them as you scroll down while keeping them in view with translateY. If you handle the keys right you can reorder them or mutate quite efficiently, which means I can manage to get a huge array rendered on iOS, but only need to maintain 20 or so DOM children.

React in a container
This is pretty straightforward. Whatever you use as your view, say an angular controller or directive, or something analogous in your framework of choice, you just need to provide a DOM element and then render the root component with the appropriate properties.

JavaScript code:
var component = React.renderComponent(YourComponent(), document.getElementsById('react-mount'));

component.setProps({newProperty: 'hello'});
/* you can use this to alter root components after a mount, if you 
 * need your surrounding app to talk to it
 */
React as the entire app
This is just a case of figuring out your state handling. As an example for my dedicated React App - my initial DOM is just a single div with the id of "<appName>app", and from there we have this component structure:
pre:
- App
  state: currentView
  - AppNavigation
  - ViewContainer(props: currentView (which is a component) )
The App on mount connects to a router service that informs which view it renders. In my case it usually just passes the viewParameters to that view component, and then the view component itself is responsible for talking to services to get the model data it needs. Again, it's really just thinking about where the state is meant to go.



There's probably a lot more I could talk about, or be more accurate in describing, but hopefully that gives you some useful info to chew on.

Maluco Marinero fucked around with this message at 13:13 on Apr 11, 2014

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

ShaunO posted:

Awesome stuff Maluco, that helps a lot and clears up in my mind the 2 way property change pattern
That gives me a good idea of how I might be able to port just the problem code to react for now to see if I get any gains

Good to hear, we did exactly that with a project about 3 months ago. We were running Angular, and it just wasn't efficient enough once the data size of the document (deliberately vague due to the product being under NDA) grew to a certain size. Load times were at 45 seconds with some of my big test data sets, which were not 'that' big. Pulling Angular out of the core of the app's render, replacing it with React, got that speed down to 3 seconds. Admittedly there was some potential for optimising Angular but we were already way over the recommended number of watchers and optimising Angular tends to mean breaking what makes it simple to use, at least in my experience with it. I'd rather get to 3 seconds and then optimise from there (which we did), rather than try to shovel us out of a 45 second hole.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Just one thing to keep in mind, recommendations are typically subjective. There isn't really one MVC framework to rule them all because they all use quite different structuring and concepts, and as a result are suited to different approaches to building applications.

Furthermore, if you're just coming in, you're likely to be learning a lot more than just the framework, but also finer points of JavaScript and what not. If that's the case I strongly recommend you just dive into which ever one feels clearest to you, whether that's because of good design, or good documentation.

You're not going to be able to correctly appraise the long term limitations or benefits choosing framework X over framework Y, hell, even experienced teams have trouble picking a winner the way the ecosystem is populated right now.

If you feel like you can get a toehold in Ember, something working and you like the feel of the code, go for it. At this point you most benefit by building and learning and not getting hung up on the choice.

I rag on Angular because I feel it has too low a performance and maintainability ceiling compared to React, but that's just for the way I'm building my apps and the kind of use cases I'm working on. Angular is a strong choice for a lot of other people and gets the job done for them. I imagine Ember is the same for those who swear by it.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Kobayashi posted:

ORM, fantastic. That was the term I'm missing, thank you.

As to your larger point, sigh, I know, you're right. In fact, I've actually taken a database class before, years and years and years ago. It was the course that convinced me that computer science was not for me. So while I have a passing familiarity with the terms you mentioned, my knowledge is so calcified as to be basically useless. My hope is that an ORM library allows me to ease my way back into databases while still affording some degree of productivity.

I really think you should look into using Rails (Ruby) or Django (Python) if you get a chance. They have ORMs, and are well suited to a beginner easing themselves back in to things because there are shitloads of decent tutorials, and the core they're built on is well established and developed.

The problem with node is you're much more likely to have trouble with dependencies, changing APIs and much weaker documentation, which could prove to get in the way. Up to you of course, but personally if I'm doing thick front end, thin back end I'll use Django and the Django Rest Framework (extra package) that means I can express my data in simple terms, setup serialisers to go from Python to JSON and be done with it with a minimum of code, all reliable.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Yep, been there, although we had some clear hair on fire problems that made the switch from Angular to React a no brainer. Performance primarily, we had a view that once the data set rose to a certain size we had pages taking 35 seconds to render in Angular + slow down for every action. My React performance test got that down to 3 seconds with more potential optimisations to be had, and from their I was pretty much told to go for it.

As for how they stack up for my mind:

Angular is good boilerplate, and very efficient on developer time for simple single page apps. It comes with plenty of batteries included so you can build something quick. However the boilerplate is almost non optional, which makes it heavy in structure. The way templates can be encoded with powerful logic can encourage a lot of bad reuse patterns that splits your codebase into lots of dependant chunks. That's not to say you can't make good reusable components in Angular, I just feel its poorly set up for it with global DI namespaces, splits between templates and code, and just a lot of tricks and gotchas to learn when you start to do things more complicated than simple bound forms.

Combined with some truly dreadful performance in complex scenarios, Angular doesn't end up saving developer time, and that gets worse the more that project deepens in complexity.

This is the key issue that I feel React has a better answer for, as a whole:

Its fast by default. Its easier to optimise from 3 second render times than 15 second render times, and if you're planning to go on mobile you need every default optimisation you can get. What works well on desktop with Angular can choke quickly with limited CPU and wasteful watch checks.

Its component driven with rigid definition of interfaces. The Property/State model actively protects the separation of concerns so you end up with components that can be reliably tested and composed into larger structures. Logic is also concentrated in JavaScript, rather than spread across HTML templates and JavaScript.

It has good allowance for testing. Recent versions have a suite of test utilities in Addons that make it dead simple to simulate events, detect sub components, etc. It also all goes back to being component driven, its easy to know all the dependencies and mock up effectively for testing.

There are less concepts to learn. React is much more concise in what it does and does not do. As a consequence the docs are well written, can be read completely in a single sitting if you wanted to, and are easy to browse. Meanwhile over in Angular land creating directives, the primary method of component reusability is such a heavy concept with lots of different stages and settings that renders the finer points hard to work with.

React dev has a slower output of functionality than Angular dev, but React components are longer lived and easier to develop cleanly, which over time results in a structure that allows you to make quite significant changes to functionality without the change having wide ranging implications. While that is possible with Angular, its arguably more difficult because of how easy you can end up with a tangled design without realising it. Angular's freedom ends up being a bit of a straight jacket.

So React might be slower to develop for in the short term, in the long term you'll have a stable and easy to predict velocity thanks to a more developer friendly framework. As for the batteries included bit, there are tonnes of libraries that do <x> better than angular. Some picks from me:

DateTime: momentjs
Translation: i18next
Keyboard: mousetrap
Promises: bluebird
Utilities: lodash

...but there's a ton out there so take your pick.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Essentially you want to prevent angular's router from firing at all if you're currently within that controller. Not something I've done before but look at this:

http://uiadventures.wordpress.com/2013/09/06/routechange-angularjs/

On top of that you manually need to make use of push state to add support for the back button.

As you observed any use of the default router will scrub the DOM within ng-view, load a fresh template, load the controller and then compile the template. The only way to stop that happening is to keep the controller in charge if there's a matching change of route.

Phone posting but hopefully that's enough to make a start?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Wheany posted:

I think I want to use React and Bootstrap together in a project. The reason is that React seems pretty nifty for building view components, and I like Bootstrap's layout, especially the responsive layout bits (from the little I've seen over a coworker's shoulder).

How dumb am I and how hopeless is this? Have I completely misunderstood what Bootstrap is for even?

Eh. Its fine, you'll be doing an awful lot of component making and class names will be flying everywhere, but bootstrap/foundation whatever is fine if you're looking to get something off the ground.

The thing about React is you really need to be strict about determining what your components actually are. Try to avoid building the markup for a whole view in one render function, trying to conform to bootstraps markup needs. You'll just make things hard to maintain down the track.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Lumpy posted:

React.js peoples: How do you do CSS transitions in React?

Say I have a bar graph type thing:

JavaScript code:
GraphThing = React.createClass({
  render: function () {
     var myStyle = {width: this.props.val + "%"};
     return ( <div className="barWrapper">
        <div className="bar" style={ myStyle } />
     </div>);
  }
});
And let us assume that said component has code that listens for an event that will change the val prop that is not shown here. This "works" in that when my event fires and the value is modified, the bar changes length, but I'd like to animate that transition via CSS. Is this possible? I'm aware of ReactCSSTransitionGroup but since I'm not using a class name (since the value is computed) I think I might be screwed.

If its just straight css transitions, even styles which are set in the style tag gets transitioned provided you're going from numeric to numeric -- no auto.

ReactTransitionGroup is for entering and exiting DOM elements where you need some frame by frame additions of classes in creation.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Lumpy posted:

Pro tip: If you typo your class name in your SASS file, your CSS transitions don't work so well. Turns out it works just fine like you said with no TransitionGroup needed. Assuming you have the right class names.... :v:

Haha yep. Just for a bit of reference for React devs, the way React renders is a lot more straightforward than you think.

Of course there's a decent amount going on in the internals, but you can simplify it down go this:

Render cycle is done in JavaScript, and each component is given a key, this is either a number when you put in component children as arguments, or a string key when you use the property 'key' on that component. This key is how React finds the element in the real DOM, which you'll see in the only proprietary tag React uses, 'data-react-id'.

When the render cycle is done, it's diffed against the last render cycle, to see what changes need to be made. In the above case it would see that the only difference is that the {style: width: '65%'} property has changed.

With that information React does the DOM operations in as simple a way as it can. Using keys and what not to reuse elements effectively.

If a key needed to be moved, it can do it without having to rebuild the entire DOM element because it knows where it was and where it needs to go. In the case of the simple style tag, the resulting Dom operation is basically equivalent to:

code:

document.querySelector('.progress-bar').style.width = '65%';

---

The main thing to remember with the React model is that it is NOT magical, it is well thought out and detailed but not to the point of a magical black box. You have good control over rendering using keys and, in rare cases, the shouldComponentUpdate method.

This means that if something works in standard HTML,CSS and a little bit of direct JavaScript, the same concepts still apply to React, you're just doing less bookkeeping.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Dr. Poz posted:

Working on an app that is long in the tooth and want to introduce a client side framework to make life easier and the team has settled on Angular. This is an existing business app so making huge changes is going to be near impossible so I'm trying to ease the transition. Is it possible to get URL parameter values without driving the entire apps ability to route through Angular routing? Currently MVC is returning the page & daata with a route like "foo/manage/1" and I wan't Angular to be able to read the "1" from the URL parameters so it can make a Ajax request for a resource. If I sound like I'm going about this backwards or wrong, please correct me.

Just use standard JavaScript to parse the location (window.location) if you intend on a controller doing it's thing without using Angulars routing. Saying this under the assumption that the way you're using Angular is not as a single page app, but rather as a part of a server delivered page that has a section you want to be Angular driven.

edit: or you can use the $location service from Angular if you want to be proper about it, that should give you access to window.location too.

Maluco Marinero fucked around with this message at 00:27 on Jul 18, 2014

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Yeah, definitely echo Lumpy and Thermopyle. I started out with Angular, and even built a bunch of things in it, I'm even working on a project where we're still using it as a sort of dependency injection wrapper, but I think there's a big problem with the Angular centric approach to doing everything.

This would be fine if Angular scaled well to performance sensitive applications, but I've come to the conclusion that if you do so you're so far beyond writing things the Angular way that a more capable UI framework would get you the results you need.

Guilty as charged as a major React fanboy on this thread, but there are some pretty compelling reasons for being so:

- Javascript direct templating through React components is god drat powerful, and allows you to have a very concise, and non wasteful DOM
- React is fast by default, and doesn't have a wasteful scope digest like Angular. This advantage can be smoothed over on strong desktop machines, but becomes extremely apparent the moment you get a weaker CPU on mobile.
- React is a small library in terms of Public API considering what it does, and its documentation is well written and concise. You can pretty much learn everything there is to know about React - in a general sense - in a day. From there, you have a very strong abstraction that I have yet to break, even with some fairly optimised use cases with reuse of elements.
- It's still JavaScript, good JavaScript devs just become better JavaScript devs with React, and the React itself is better suited to embedding in any project. Angular is not really JavaScript at the end of the day, it's a mishmash of templating and javascript code, forming a web of tangled concepts like services, controllers, directives, and filters.

Now, while it is true that React can't do everything Angular can do (which is why it's still a dependency injection wrapper in one of our projects - also we don't want to slow down on the rewrite), the core problems with rendering Angular templates cannot be discarded without also discarding the majority of concepts, scope, directives, filters, controllers, all almost stripped bare.

While big frameworks will always have a place, I think for serious app development they'll go the way of the dodo in favour of small libraries that do one thing well. I'll have more to say on this over time I imagine, (I'd love to write a book on this poo poo, dunno if anyone will listen but I'm kinda keen to put it to txt file), but I think that'll come after I've gotten deeper into some projects I have under way.

Maluco Marinero fucked around with this message at 23:05 on Sep 2, 2014

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
If you like the look of Vue go for it, you'll be learning anyway so you can't expect quality engineering from your first pass no matter how much you try to analyse and plan.

Get runs on the board, you're working with HTML/CSS/JS and Vue looks pretty straightforward so jump on in.

However, knockout will have more community resources available to learn from, even if the API is older and doesn't have as much magic, you will be able to get the job done.

Another shop I've worked for in the past use Knockout to good effect and move pretty quickly with it, so I wouldn't say its a bad choice either.

In the end of the day, at this stage you should optimise for months of your life because you don't know enough yet to optimise for anything else, with your project or with the frameworks. Vue is a bit unknown to me, and Google isn't exactly a tick of approval when it comes to libraries and APIs (they don't tend to document or support them particularly well), but all you're risking at this point is a bit of time where you were learning anyway. Pick one and start coding, don't delay. :)

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
For anyone who just wants to ajaxify a more simple website to behave like a single page app try http://sennajs.com , I haven't used it but looking at the API it seems more geared towards that use case.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

fuf posted:

I'd looked at React in the past and just had a look at react-router.

The thing I'm not sure about is React components only ever seem to have really small html snippets defined right there in the app code, like this:

code:
var Header = React.createClass({
  render: function() {
    return (
      <header>
        <ul>
          <li><a href="/">Dashboard</a></li>
          <li><a href="/inbox">Inbox</a></li>
          <li><a href="/calendar">Calendar</a></li>
        </ul>
        Logged in as Joe
      </header>
    );
  }
});
But I can't really do this for a full page's worth of content with paragraphs and images etc. Is there a method which uses external html files like with Angular's TemplateUrl?

You can use the dangerouslySetInnerHTML property to use a string as the HTML of a DOM element, but tbqh you may get along just fine with a combination of 'flatiron director' for your routing and jQuery for getting snippets and injecting them. You barely need any front end framework if that's all you're doing, but I'm saying that with no knowledge of exactly what you're doing.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
I'm using i18next, plenty of tools around it, and reasonably well though out. Usable with browserify if you need to embed it into the app bundle. http://i18next.com

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Pollyanna posted:

Front-end, maybe. But I still don't quite get what all this poo poo does in a Backbone application, or why I need all of it:
<words>
A better way to think about these frameworks is not necessarily think about how they all work under the hood. They aren't created equal.

React has what is more or less a render pipeline that takes Javascript and transforms it into a DOM representation. Angular is a combination of a templating language, directives, controllers, and services, that forms a system for making changes to Javascript and having those changes propagate to the templating layer, and the directives support binding to propagate changes in the other direction.

There isn't necessarily a common thread in implementation here. What is common is that they have an opinionated, structured way to achieve a goal, which is a web application interface. The purpose of 'all this poo poo' is to provide you enough tools within the opinionated framework to build your web application in a way that is structured and maintainable. The issue with jQuery is that it's difficult to build a sane maintainable structure of abstraction on the fly, you'll gently caress it up and couple things too hard or make an incomprehensible mess.

Frameworks have the experience invested into a structure that is usable to create larger scale applications. That said, on the top of this, that sort of means you have to buy the opinion of whichever framework you use. Trying to build an app with the opinions of Ember within an Angular app is destined for failure just as much as your jQuery cobble together.

Learn deeper about whichever framework you hitch your wagon to, but trying to learn how they ALL work will have you pretty busy for marginal gain depending on what you then do with that knowledge. It's better to find a framework that speaks to you and allows you to get what you need done, build some stuff and learn it over the process. In some ways I think the more you need to know about the internals, the worse an abstraction that framework is. It's part of why I don't depend on Angular, it's scope digest system is total black box to me, and the process is way too complex for me to enjoy having to dive into, so when I have performance issues it can become very difficult (to me) to break them down in a way that preserves the abstractions Angular use, like templating, data-binding, and the scope.

In a way that's why I gravitate towards things like React because I'd rather have smaller libraries with reliable abstractions than bigger libraries/frameworks with blind spots. That said, that means you need to think a lot more about your tech and structure choices, rather than just taking what you're given by the mega framework. Angular solves that problem really well by the way, it just has more overhead than I feel is acceptable for web applications, especially in the context of mobile applications where there is significantly lower calculation ceiling, where all these event listeners and bindings and general calculation hits the limits real fast.

</words>

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Corla Plankun posted:

Is there a name for the kind of dialog with two list boxes and an Add/Remove button in the middle?

The best example I can think of is Winamp's column headers dialog. The left list box has all of the possible headers and the right one is all the active headers.

To avoid the XY Problem: I'm trying to think of a way to easily select a lot (~50) of CSVs from a folder full of them, and then create some d3 graphics based on the selection. The dialog I'm thinking of seems like the easiest way to do that but maybe I am missing something obvious.

A filtered multiple select or multiple select list box seems to bring up results. Django admin has a good one but stand-alone I only found http://loudev.com so far...

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
He's a framework developer with an axe to grind and hits to pull in. I actually agree that for a lot of apps Angular is unsuited, slow, and is bloated with too many features that add unnecessary complexity...

But it's all argued from the point of view that his framework is the true way of doing things, so honestly I start to tune out there.

Angular IS good for beginners despite what I said because you can to some basic functionality without being an experienced developer. Angular has most of your fundamental architectural decisions made so you just follow that and you're good to go.

I sort of hate that so many articles are just thinly veiled plugs for their own 'brand' that run out linkbait, I hate seeing them on sidebar.io too cause it just wastes peoples time on promotion pieces.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Newf posted:

Yet here we are :)

It makes a freaking huge difference to any complicated site. If your render times are tight, lovely CSS rules are a great way to make them poo poo the bed, especially on Mobile or old rigs.

My rule of thumb is to pretty heavily use BEM, and only use classes. Why you ask, well every tag only selector you, such as -- .something a { rules } -- requires the browser to traverse every single instance of a .something to find if it has a child a, or the reverse. The flatter you can keep your hierarchy, the less grabby every rule can be requiring far less DOM traversal. On its own its trivial, but it multiplies pretty quickly with a poor approach.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Meh, kicking it down the can means you may have to rewrite your CSS and HTML and JavaScript to accommodate the rule changes. Actual separation of concerns is kind of a pipe dream, once you find out your CSS is garbage your usually tacking on a good amount of time to clean house if its critical.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Number 2 is how I'd handle it, but you need to have some way to ensure data remains in sync between the two. Its more or less a Activities store and an ActiveActivity store (bad name I know). The good thing about this is it provides a more focussed action structure, the Activities list would only need broader actions like delete activity, move, whatevs.

There's probably some stuff to do be done in there like caching Activity details so you don't have to hit the server for more if it already got that activity, but that really depends on the use case I guess.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Are you searching for a mounted element within a tree, or just a class that you can use somewhere. If its the latter React doesn't actually have a registry of classes, but you could easily create an object that'll hold class references yourself.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Thermopyle posted:

I don't really know anyone who doesn't use JSX.

(queue everyone posting they don't)

Yep, I don't really like jsx at all, that said I barely gave it a chance. I just import the Dom elements I need with destructured assignment in coffescript or es6.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
I made a little library for managing CSS driven transitions/animations, especially in cases where you need to do measurement and tight frame timing.

https://github.com/weareoffsider/css-driven

I've used it on bits and pieces here and there where I need a little more control that CSS but I don't want to go full js with velocity. Its tricky but with requestAnimationFrame its possible to get the render to play pretty predictably, of course it's key to avoid doing animations other than transform+opacity if you want to keep the frame rate up though.

When you're working with React the main thing to remember is to clean up your poo poo, you can get the DOM node just fine so your focus should just be to trigger the anim, do the anim, and then clean up back to a state that can reconcile with React so it doesn't freak out or break changes.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Yeah, you don't have to use react transition groups top level api, go for the low level API that let's you define your transition end callbacks. The DOM element will stick around as long as you need it to.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
I don't use SASS anymore for that reason. Less CSS is actually pretty good these days, it has a JavaScript API for writing custom plugins, and doesn't have split implementations like SASS (libsass/rubysass) resulting in fragmentation and guess the version bs.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
If you use the displayName attribute in your components, it'll be able to tell you the name of the component that contained the key error, which is usually enough for you to track it down.

Adbot
ADBOT LOVES YOU

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Yeah, the back end needs login credentials of some kind just like a standard website, usually a username/password login followed up with the creation of a securely randomized string as their session token. No difference, although you have more options for storage, cookies, local storage, memory only etc.

How long lived your session token is depends on your security requirements.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply