I've been comparing js mvc's and noticed that a nice amount of people are bragging on the "live binding" that canjs does. Can someone explain what exactly it is and how it helps in comparison to the other popular mvc's like backbonejs, spine, etc...
Backbone does support implementing model binding, but it's not automatic as in some other client-side application frameworks, for example, AngularJS's data-binding through ng-controller
or EmberJS's bindAttr
.
For some really rudimentary code to update views as a model's state changes, use Backbone.View
's events
object, as in this example:
var ExampleView = Backbone.View.extend({
id: 'myView',
events: {
// using an #id selector here is also acceptable
'change [data-attrname=name]': function(e) {
// update the value in the model
this.model.set('name', $(e.target).val());
}
},
initialize: function(options) {
this.model.on('change', this.render, this);
},
render: function() {
var html = _.template('<h1 data-attrname="name"><%= name %></h1>',
this.model.toJSON());
this.$el.html(html);
return this;
}
});
Which will render the following HTML (myView
is the div implicitly created by ExampleView):
<div id="myView">
<h1 data-attrname="name"></h1>
</div>
This is essentially doing binding manually from the UI and wholesale (re-render
ing the entire view) when the model changes. Backbone is intentionally designed to be less opinionated than some other frameworks, to allow you to implement things as you see fit with the addition of other libraries.
For some more sophisticated techniques on how to model bind more automatically, here are a few resources listed by their authors: