Jax is right that you don't need to manually bind View methods and events in the latest version of Backbone (currently 1.1.0). There are earlier versions where this is also true, but I do not remember which ones.
There are times when you need to bind view methods so that they work correctly. These cases are the main areas of Javascript and are not specifically related to Backbone JS.
_.bindAll. , _.bind, Underscore JS.
, Backbone, _.bind. Backbone Events. , Collection Model, Events, .
, , .
this.collection.on('add', this.appendItem, this);
this.model.on('change', this.render, this);
render. render , .
:
this.collection.bind('add', this.appendItem, this);
on bind, , on. bind . , Backbone on off bind unbind.
jsFiddles, , . : http://arturadib.com/hello-backbonejs/docs/5.html
, . , , , , Backbone 1.10. , _.bindAll.
1 : http://jsfiddle.net/ChTjs/
:
initialize: function() {
this.collection = new List();
this.collection.on('add', this.appendItem, this);
this.collection.on('add', this.updateCount, this);
this.collection.on('remove', this.updateCount, this);
this.counter = 0;
this.render();
},
:
this.model.on('change', this.render, this);
this.model.on('remove', this.unrender, this);
jsFiddle, . http://jsfiddle.net/LpEW8/1/
, . , Backbone. Binding "this"
2
, listenTo. , /, listenTo. this on. , , on
, :
this.collection.on('add', this.appendItem, this);
this.collection.on('add', this.updateCount, this);
this.collection.on('remove', this.updateCount, this);
:
this.listenTo(this.collection, 'add', this.appendItem);
this.listenTo(this.collection, 'add', this.updateCount);
this.listenTo(this.collection, 'remove', this.updateCount);
listenTo Backbone docs: http://backbonejs.org/#Events-listenTo
: http://jsfiddle.net/ChTjs/2/