Backbone, trigger an events when all is loaded
In my backbone app I load 3 Collections and I bind the "reset" event at the render function. So, in this way, when I fetch the Collections, I print the various results, but not simultaneously.
I would use the jquery deferred methods ($.when, $.then) to print all simultaneously, how to do this if I use the "bind events" on the views?
this is the code:
Router:
App.Routers.test1 = Backbone.Router.extend({
routes: {
"/test" : "test"
},
initialize: function() {
// Models
this.Models_1 = new App.Collections.coll_1;
this.Models_2 = new App.Collections.coll_2;
this.Models_3 = new App.Collections.coll_3;
// Views
this.View_1 = new App.Views.view_1( {model: this.Models_1} );
this.View_2 = new App.Views.view_2( {model: this.Models_2} );
this.View_3 = new App.Views.view_3( {model: this.Models_3} );
},
test: functi开发者_如何学Pythonon() {
$.when(
this.Models_1.fetch(),
this.Models_2.fetch(),
this.Models_3.fetch()
).then(function() {
// ?????????????????????????
// What should I do here?
// ?????????????????????????
});
}
});
View 1:
App.Views.view_1 = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('reset', this.render);
},
render: function() {
// print the data...
}
});
test: function() {
$.when(
this.Models_1.fetch({silent: YES}), // silent will prevent triggering any events on reset or add
this.Models_2.fetch({silent: YES}),
this.Models_3.fetch({silent: YES})
).then(_.bind(function() {
this.Models_1.trigger('reset'); // manually trigger events in sequence you want
this.Models_3.trigger('reset');
this.Models_2.trigger('reset');
}, this));
}
Not sure where you are going with your deferred events. Backbone already has a way to do this.
In your view, bind the event "refresh" from the collection to the view render function. Whenever you will call fetch on the collection, the refresh event will be triggered and your view rerendered.
Perhaps underscores defer is the method you're looking for?
Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating.
精彩评论