Sort of a novice javascript person reading a backbone.js tutorial http://arturadib.com/hello-backbonejs/docs/5.html and have a few questions about some of the code the author uses.
In the initialize function below, the author binds
this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);
I’m assuming this means the render function is called on the ‘this’ object whenever the change function is called, and unrenderis run whenever remove is called. The problem, for me, is that there is a defined function 'remove' in his code, but no defined function 'change'
Question: Do change and remove refer to jquery functions or does the remove function refer to the remove function defined in the code (i.e. it overrides the jquery function) while change refers to the jquery function. If the latter, what exactly triggers the 'change' function if it’s never explicitly called and, hence, the render function?
Code
var ItemView = Backbone.View.extend({
tagName: 'li', // name of tag to be created
events: {
'click span.swap': 'swap',
'click span.delete': 'remove'
},
initialize: function(){
_.bindAll(this, 'render', 'unrender', 'swap', 'remove'); // every function that uses 'this' as the current object should be in here
this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);
},
render: function(){
$(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
return this; // for chainable calls, like .render().el
},
unrender: function(){
$(this.el).remove();
},
swap: function(){
var swapped = {
part1: this.model.get('part2'),
part2: this.model.get('part1')
};
this.model.set(swapped);
},
remove: function(){
this.model.destroy();
}
});
The
changeandremoveare Backbone events, not jQuery events. These:mean that
this.renderwill be called when the model triggers achangeevent andthis.unrenderwill be called when the model triggers aremoveevent. Thesetmethod on models:is one way to trigger a model’s
changeevent,unsetandclearwill also triggerchangeevents.removeevents generally come from collections but the collection will send them through the appropriate models in case there are views listening.You might want to read the (quite good) Backbone documentation and review the Catalog of Events in particular.