Backbone usage sample
This code can be executed into javascript console while visiting http://backbonejs.org
Create a model class.
var MyModelClass = Backbone.Model.extend({ });
Use the model with your data.
var myModelInstance = new MyModelClass({
'name': 'John',
'surname': 'Doe'
});
Create a view class, bind to an element of the DOM and bind model changes to render method.
var MyViewClass = Backbone.View.extend({
el: '.container p:eq(1)',
initialize: function () {
this.model.bind('change', this.render, this);
},
render: function () {
this.$el.html('<p>' + this.model.get('name') + ' ' + this.model.get('surname') + '</p>');
_.bindAll(this);
return this;
}
});
Use the view by creating an instance with the model.
var myViewInstance = new MyViewClass({
model: myModelInstance
});
Render the view.
myViewInstance.render();
Change an attribute of the model; this will trigger DOM elements refresh.
myViewInstance.model.set('name', 'Jack');
Written by Matteo Caberlotto
Related protips
1 Response
If only I had read this before...
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#