Skip to content

Instantly share code, notes, and snippets.

@rharriso
Created June 6, 2012 06:50
Show Gist options
  • Save rharriso/2880328 to your computer and use it in GitHub Desktop.
Save rharriso/2880328 to your computer and use it in GitHub Desktop.
Backbone.js: Handle multiple binds to the same model, with different contexts.
/*
Backbone event binding works very well. It is possible to remove listeners from specific context without specifying a named function
*/
//set up model
var Ork = Backbone.Model.extend({
defaults:{ says: "Waaaaaagh" }
});
var o = new Ork();
//create two contexts
var context1 = {};
var context2 = {};
//add identical event listener with both context
o.on("change", function(){
console.log("Ork1 says ", o.get("says"));
}, context1);
o.on("change", function(){
console.log("Ork2 says ", o.get("says"));
}, context2);
o.set("says", "Red makes it FASTA!!");
//Ork1 says Red makes it FASTA!!
//Ork2 says Red makes it FASTA!!
//remove event from one context
o.off("change", null, context2);
o.set("says", "Waaaaagh!!!!");
//Ork1 says Waaaaagh!!!!
/*
Situation: A list of models. The list needs to listen to changes in the model, and re render the
*/
/*
Class: Parent View
Renders series of subviews.
*/
var ParentView = Backbone.View.extend({
....
/*
Method: renderModelAtIndex
Parameters:
index (int) - index of the model to be rendered in list
*/
renderSubViewAtIndex: function(index){
//pull item out of model list
var item = modelAtIndex(index);
//unbind change events from this view
item.off("change", null, this);
//bind event to this view
var t = this;
item.on("change", function(){
t.renderViewAtIndex(index);
}, this);
//do more child view stuff
}
....
});
/*
Class: ChildView
Inherits from parent view, uses same rendering, listens to same object, exits at the same time.
*/
var ChildView = ParentView.extend({
....
renderViewAtIndex: function(index){
//do child stuff
//parent method called as child view,
//context is different, so the bindings don't
//interfere
ParentView.prototype.renderViewAtIndex.call(this, index);
//do more child stuff
}
....
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment