[StackOverflow] Backbone.js, models update
How update directly a view when a model has changed.
http://stackoverflow.com/questions/8739099/how-backbone-and-knockout-make-views-change-when-modle-update
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<div id="content"></div>
<a href="#" id="changeModel">Change Model</a>
CSS
#content {
padding: 5px;
background: rgb(240,240,240);
}
JavaScript
// Create Model
var Model = Backbone.Model.extend();
// Create View
var View = Backbone.View.extend({
initialize: function () {
// Bind the change event of the model to this view
// It will call this.render() for each change on the model
this.model.bind('change', this.render, this);
// render the view
this.render();
},
render: function () {
$('#content').html('Name : ' + this.model.toJSON().name);
}
});
// Create a model
var model = new Model({ name: 'TEST' });
// Create a view and bien the model to this view
var view = new View({ model: model });
$('#changeModel').click(function () {
model.set({ name: 'STACK' });
});