Knockout v3.0.0 released
knockoutjs.com
knockoutjs.com
Looks like this version makes what I believe to be Knockout's biggest strength (the data binding) that much stronger.
Knockout got attention, but there are so many frameworks that it is not so easy to see the big advantage of one.
I tend to use Angular, but recently I jumped onto a project and crunched through some work by dropping Knockout into it. The learning curve is small, and I was able to finish off the feature quickly.
My complaint (probably more relevant to hardwaresofton) is that I like my MVVM to have a type resolution system, ok in javascript this is hard, but if I've got one ViewModel for the NavBar, it would be nice to be able to better state the one for the MainContentArea. ko.ApplyBinding(vm, someJQuery) just doesn't strike me as elegant!
That said, I liked knockout when looked at it, I just looked at Angular shortly after and fell in love. Annnd, I haven't looked at the new version, so grain of salt.
We went to that after hell with pages littered with applyBinding calls.
The main difference seems to be that in Knockout has 'observables' that are part of your view model, whereas with Ractive you interact with your view model via Ractive's functions.
One key area of performance where js rendered UI helps a lot is in customizing an otherwise uniformly served (and cached) page. 95% of the page is uniform to everybody, so render that server side and cache the heck out of it (varnish or whatever). Then, bind the pieces of the UI after page load and customize them based on the user - their login status, their location, etc. We use this approach at food52.com and food52.com/provisions.
However, I came to a team that couldn't GROK the scope of Angular, and Knockout.JS was so much, easier for them to approach. They are now into the whole reactive UI thing, have their code organized into view models. Now, over time, I can start sprinkling in Q library, and other Angular-esqe libraries and they'll be a lot happier. Another nice thing about Knockout.JS that I've come to appreciate is that it's about 10x easier to make custom binding handlers than it is to create Angular directives. And we had to write a custom service layer anyway, so it's not like we needed that from the Angular library.
Now you have a full stack in like 50k.
I always check my web work on as many browsers as possible anyway, since quirks abound at all levels of the stack.
The thing I really like about Knockout is that I don't find the complexity to ramp up as much as it does in Angular. It's also super easy to just insert it into any page and use just the functionality I need. It's also got great performance when it comes to 2 way binding.
I built a small, single page app, http://fixparser.targetcompid.com using knockout. I use knockout fairly heavily and it was easy to pick up for someone like myself, who is not a front-end/web developer.
Since my plan was to overhaul the site, I tried to use angular but found that it was much more difficult to use. Knockout provides the functionality I need and provides it very well. Their core members are extremely helpful on their own newsgroup as well as on stackoverflow.
If I was doing a large app, with a bunch of developers, I suppose I would take another look at angular. For now, I'm happy to stick to KO for the foreseeable future.
For me, there are several things I like about Knockout as someone who's not a primarily frontend developer:
1) Obviousness of purpose. The thing I hate the most about frontend development is the lack of visibility into what is actually bound to an object. When I run into UI code that's not using some kind of framework like Knockout, inevitably the UI interactions are typically performed with jQuery bindings, and often they aren't terribly straightforward to find for anyone who didn't initially develop it ("what, you bound a mouseover action to everything that fits '.mouseoverable > li > ul > li > .mousey'?")
2) Clearly defined interaction models. I like creating and populating the ViewModel, and thus having a very clear place in the Javascript where I know the business logic and data for the frontend are going to live. When I create the ViewModel as its own Javascript object, I can define the full contract of what data the application needs and what operations can be done against it in a manner that I can quickly locate and fix up later.
3) Syncing of frontend state with data state. (of course, this is an obvious benefit, but...) I love that, once I've defined these obvious bindings, I can then focus more on my model and less on what is bound to that model. It gives me the ability to separate out my concerns, at least more than a scattering of one-off jQuery bindings would.
Knockout provides an obviousness of binding not only because all interactions between the UI, the user, and the model are supposed to happen through these bindings, but because the bindings are supposed to live on the element being interacted with/displayed itself. This made a huge difference for me, as someone who likes to see an obvious relationship between the view and the underlying logic that's modifying or creating that view. The concept of observable properties also felt natural to me, and I didn't mind taking the time to make rich ViewModel objects that had methods attached to them representing actions, and "ko.computed"s when I had more complex scenarios in which I wanted to watch for (or perform) an update.
However, our frontend guys hated it, and I can understand why they feel that way (though I disagree with them on many of these points, and would like to win them over). For them:
1) "We're moving backwards." It's a dramatically different approach that feels counterintuitive - in fact, for frontend developers who've been told their entire career to never put event handlers on the attributes of an element itself, it feels like a step backward evolutionarily. It feels, to them, like you might as well be going back to "onclick=''" bindings.
2) "More upfront work." It's a more upfront work to create and maintain solid and coherent ViewModel objects, particularly when Knockout provides the tempting - but often fragile - alternative of calling "ko.mapping.fromJSON" or "ko.mapping.fromJS" that will essentially make a dumb ViewModel for you, but will also make everything observable and won't give you any of the benefits of creating your own ViewModel with reasonable business logic, computeds, etc... This not only ends up making the bindings feel messy as they start performing complex logic directly in the binding where a computed or method would do, but it reinforces that bad "onclick=" binding feeling that they hate.
3) "We have to surrender control of the DOM." The real killer for them is that, once the DOM is being managed by Knockout, you essentially have to give your control of the DOM over to Knockout. If you start fiddling with DOM elements with your own custom jQuery handlers instead of through custom (or built in) bindings, Knockout is going to inevitably run over your changes in unexpected ways as it itself modifies the DOM. Asking the frontend developers to make custom bindings is, unfortunately, asking for more work (and less intuitive work) than just making a jQuery binding, and thus it presents itself as a lot of additional code.
4) "The path for mixing 'common' ViewModels with 'page specific' ViewModels is not clear." This is one I still struggle with in trying to help find a clear path for them. Let's say that a page loads with a bunch of sections that are common to every page, and there are also page specific data and operations that need to be loaded. Knockout only lets you bind one ViewModel object to a given set of DOM elements at a time, which makes this difficult. My gut is that, if we were to create these ViewModel objects in such a way that a common "binding" Javascript block of code - run after all ViewModel objects for the page were both created and combined into a single over-arching object - existed, then they could all live together. This solution is fragile, however - that means every binding would need to be bound to some object off of that single ViewModel object, which could be prone to breakage as these models change. Essentially, bindings (or DOM elements with appropriate "with:" bindings to scope out what part of that larger ViewModel you cared about) would have to be created with this larger overall ViewModel in mind. The proposals don't sound great when I talk to people about them, and I can understand their hesitation. (if any of you have good alternatives, I'd love to hear them)
5) "We dislike having 'logic bindings' or 'placeholder bindings'." Frequently, the data for the ViewModel isn't actually loaded yet by the time you need to bind. The way of preventing the bindings that require that data from breaking is to have boundary bindings wrapping them, such as checking if the object is loaded or the data you want isn't null... but now you've got essentially boundary checks sitting in the DOM. They dislike those - understandably - and they dislike "with" bindings as well. It all feels like fluff that they shouldn't have to worry about, and that crowds up the view. This is another one for which I don't have a good response or alternative.
Anyways, Knockout definitely has both good and bad elements to it. I encourage everyone to give it a try. You may love it - as I do - despite its flaws, or you may hate it! But give it a shot, it may be a handy tool for you.
1) the pendulum is currently swinging backwards from the "no logic in the HTML" and is heading towards the "all logic in the HTML". Knockout, angular and ember all use declarative bindings, which is the complete opposite to what jQuery code was like. I think it is a good idea, as it makes it easy to understand how a dom element is supposed to behave. But the pendulum will probably swing back in the other direction again in a few years, and somewhere in the middle is likely the optimum.
2) fromJS and fromJSON are dangerous and should be avoided. It might be more work to manually write things out field by field, but it makes things a lot easier to debug and understand later on (just like data-bind makes interactive dom easier to understand than jQuery magic). Easy to write does not equal easy to read or maintain.
3) jQuery should be forbidden in a knockout.js project, except (maybe) inside custom bindings. This does make some things which are easy with pure javascript difficult, and that is unfortunate. I still haven't found a good solution to this.
4) shameless plug: I'm working on a framework which solves this, called ordnungJS (http://ordnungJS.com) it is not well documented yet, but I have used it in production code and it works well. I'll improve the documentation when it reaches a more stable version, and write a short tutorial on how to use it.
That being said, my KO education is not as good, so it's highly possible that I made design mistakes that made the project more painful than necessary. Nevertheless, I don't hesitate to recommend Angular; I normally dislike web development but Angular is quite a lot of fun to use.
I also personally prefer how Angular doesn't force you to use getters or setters, although it does involve more "magic" behind the scenes stuff which can be confusing.
But the solution we use is something completely different which is hard to explain in a single post. It is based on CQRS and provides not only a way to communicate with the server, but validation of parameters. This works very well with Knockout observables, since you can create an object once and then execute it multiple times, when the observables have changed.
See here: http://stackoverflow.com/questions/9254632/how-to-stop-knock...
Also note that you can configure it as a virtual element, so you can use the <!--ko stopBindings: true--> syntax.
(Though the Frontend guys will complain about another 'logic binding' in their Views... I don't know what I can do about that other than to point out that the benefits are worth having those in the views. Virtual elements or not, these kinds of bindings annoy them. I see it as the price you pay for all of the benefits personally, but I'm a person who can't stand hunting for arbitrary jQuery bindings to figure out why a behavior occurred.)
3)I found binding handlers in the beginning to be more work to write, but in the long run the code is less brittle and much more reusable (not tied to a specific element). Although pitching to front end folks may not care about this.
4) If I'm understanding what you are saying this sounds to me like you are hitting the limits of Knockout. Durandal has a much better structured system for models/views and nested bindings. The compose syntax in Durandal also comparable to the template binding in knockout, although a lot more flexible. Durandal is built on knockout so much of what you already know will just work.
5) Agreed
Indeed, my solution for (2) is to say "hey, let's make a real set of ViewModel objects". I have an internal-only project that I built myself, which was basically a fairly complex experiment in using Knockout - and making the ViewModel objects myself really made a difference in how the whole application felt, it felt great. But it was a hard sell - one that I lost - when I tried to sell them on it in general.
And indeed, I don't know if I'll ever find a solution around (5). I feel like it's a small price to pay for the benefits personally, but it is a price to be paid. :(
Yes, it is worth the effort to check out. While you can mash several things like sammy and other frameworks to make your own SPA type solution, Durandal already has done it for you (built on require.js, sammy, and knockout)
Knockout (and other libraries like it) turn manual DOM manipulation into something stateful and object-based.
That said, unobtrusive event handling that comes packaged with knockout might make the transition easier for them (http://knockoutjs.com/documentation/unobtrusive-event-handli...).
First, I wasn't questioning the architectural soundness of Knockout. I think it's very sound, and I like it.
Second, I also agree with you that the DOM is available to the developer - however, if you go about blowing away and re-creating DOM elements that should have bindings on them (for example), you're going to have a bad time. This was something counterintuitive to our Frontend developers. In situations where you want to create or remove DOM elements with Knockout bindings, you really should be using Knockout's bindings (or your own custom Knockout bindings) itself to do it, otherwise you're working pretty hard against the grain. I don't personally see a problem with that - so I agree with you that the DOM is available for change - but that was hard to sell to others. :shrug: maybe I'm just a bad salesman.
EDIT: Ah, I think I can see why you feel this way. I should put the counterpoints I put above in quotes, as they don't actually reflect how I feel. I can see how someone skimming would think I actually believe them to be true. I personally have a very favorable opinion of Knockout. I can, however, see why it's a hard sell for some frontend developers. I can't blame them for feeling that way given their points above, though I would like to believe that I can win them over with my counterpoints to it over time. Whether that actually happens... we'll see.
I could also use some more ammunition in that fight, so if you have good alternatives or approaches that I'm ignorant of, I'd be extremely glad to hear them!
Consistency and maintainability of a codebase is a big factor for me. If I have a large project with knockout I can nearly guarantee a fairly similar style across the codebase. Time spent being the owner of a large project convinces me that a framework like knockout is important. So for the life time of the project it gives new developers coming onboard a good idea what to expect from the outset.
I've never been good at convincing people of things, however, so it's been an uphill battle - one that I lost a lot of ground on early, and I feel like a lot of our frontend codebase suffered as a result. I do feel like they're slowly starting to warm up to the benefits of it now that they've had some maintenance problems with the current approach, but that's similar to sending an innocent man to prison for several years before discovering he's innocent - it'll take a while to undo what's been done, if it can be undone.
Now, none of this is to say that they're bad developers. They make amazing UIs that I couldn't even conceptualize (me being a backend jockey who is terrible at making things look good). It's hard for someone to hear about an entirely new approach to what they've been doing for 5-10 years and to accept it off the bat, so I don't blame them at all. I do still hope that they'll come over entirely to the concept. We'll see what happens. :)
I feel like many of your team's complaints are due to the fact that they are old school web developers who have probably never wrote apps on the desktop before, where 2-way bindings are standard. The jQuery style of event binding is extremely brittle because it requires the DOM to have a specific structure.
Having said that, the mistake I made early was to use ko.mapping.fromJSON and fromJS to blindly generate the view model, which turns every field into an observable. It was very easy to get going and get it working fast, but I ran into performance problem later on with hundreds or thousands records. The advice to take the time to build your own view model and decide which field needs to be observable and which field can stay plain old Javascript object is very sensible.
I actually was looking more for articles that gave the philosophy behind Knockout though, not a comparison with Angular - I mentioned that more as a reference to my experience with client-side MVC. I would like to understand other frameworks independently from anything else - I want to know what they are trying to accomplish without any opinions.
"Knockout is a library that binds Javascript objects to DOM nodes."
It accomplishes that task amazingly well. It essentially takes this DOM node:
<a data-bind="attr: {href: link()}, text: title()"></a>
And let's you bind a JS object like this to it: var my_view_model = {
link: ko.observable("#foobar"),
title: ko.observable("A link")
}
Then, knockout watches the `my_view_model.link` and `my_view_model.title` attributes for changes. When it "observes" a change of their value, it updates the DOM.That's about all you need to grok to see value out of Knockout. If you can get your data into JS objects, Knockout can do a bang-up job of keeping your DOM in sync with your data. As a "backend guy" that eliminates a whole lot of boilerplate JS I used to write whenever my data changed or I needed to keep track of state.
Knockout does more, of course, but from then on it's mainly about adopting it to your use case (Do I mix it with Django templates? Do I just go with a static-only frontend? How do I manage AJAX requests to keep my JS objects data up-to-date?)
The other thing I adore is a lack of magic. This means more code but this also means I can understand what's going on after a long break from the project.
http://anexiledderryman.com/post/50565922110/javascript-sing...
Off topic, but would mind sharing what you used to create the diagram?
I haven't done a single page app again until a few weeks ago when I started playing with a side project. After looking at the options now available I settled on backbone + bacon.js (baconbone?). Once I got my head around functional reactive programming using the bacon.js eventstreams and properties vastly simplified my frontend code. At least for me changing the representation of the frontend from a static state to one of a stream of changes where the state is an intrinsic value of the event stream clicked. YMMV.
It doesn't force any kinds of rigid conventions on the code, which is good if you're adding it to a already existent project.
It is kind of fiddly having multiple layers of observables
ListOfPeople -> ListOfDetails
where both sets of lists are updated in real time to the server in JSON, but overall I found it remarkable easy to get into.
Beware, if you are thinking of using Knockout.js for a mobile friendly app, the binding / events can easily slow down your app.
We evaluated a number of options and found Knockout to deliver the fewest number surprises.
Knockout's primitives make it possible to design elegant solutions to problems that frequently seem to result in unmaintainable code.
Kudos to the Knockout team!
We haven't published the official 3.0 announcement yet, but you can find an overview of what's new on my Release Candidate/Beta blog posts:
* http://blog.stevensanderson.com/2013/10/08/knockout-3-0-rele...
* http://blog.stevensanderson.com/2013/07/09/knockout-v2-3-0-r...
The version of the specs published to knockoutjs.com didn't match the final release. I've just updated them. Please let us know if anything is still failing, preferably at https://github.com/knockout/knockout/issues