public
Created

onReset callbacks with Backbone collections

  • Download Gist
1.js
JavaScript
1 2 3 4 5 6 7 8 9
personById: function(id){
var person = new Person();
person.id = id;
person.fetch({
success: function(model, response){
App.showPerson(model);
}
})
}
2.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11
personById: function(id){
var persons = new PersonCollection();
 
// note that "bind" is now "on" in Backbone v0.9.x
persons.on("reset", function(collection, response){
var person = collection.get(id);
App.showPerson(person);
});
 
persons.fetch();
}
3.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// App.js
// ------
// some initialization code that happens elsewhere, using Backbone.Marionette
 
App.addInitializer(function(){
App.persons = new PersonCollection();
App.persons.fetch();
});
 
 
 
// PersonRouter.js
// ---------------
// The router callback that needs to get the person
 
personById: function(id){
App.persons.onReset(function(collection){
var person = collection.get(id);
App.showPerson(person);
});
}
4.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
OnResetCollection = Backbone.Collection.extend({
constructor: function(){
var args = slice(arguments);
Backbone.Collection.prototype.constructor.apply(this, args);
 
this.onResetCallbacks = [];
this.on("reset", this.collectionReset, this);
},
 
onReset: function(callback){
this.onResetCallbacks.push(callback);
this.collectionLoaded && this.fireResetCallbacks();
},
 
collectionReset: function(){
if (!this.collectionLoaded) {
this.collectionLoaded = true
}
this.fireResetCallbacks();
},
 
fireResetCallbacks: function(){
var callback = this.onResetCallbacks.pop();
if (callback){
callback(this);
this.fireResetCallbacks();
}
}
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.