After calling collection.fetch({ add: true }) on a Backbone collection, I'd like to trigger an event once the view of the updated collection has finished rendering.
The "collection view" has an "add" method, which generates an "item view" for each new item in the collection, calls "render" on that view, and adds it to the collection view.
Is there a way to trigger an event when fetching a collection has finished, and all items have been added and rendered?
After calling collection.fetch({ add: true }) on a Backbone collection, I'd like to trigger an event once the view of the updated collection has finished rendering.
The "collection view" has an "add" method, which generates an "item view" for each new item in the collection, calls "render" on that view, and adds it to the collection view.
Is there a way to trigger an event when fetching a collection has finished, and all items have been added and rendered?
Share Improve this question edited Nov 28, 2012 at 17:36 Alf Eaton asked Nov 28, 2012 at 12:28 Alf EatonAlf Eaton 5,5034 gold badges47 silver badges52 bronze badges2 Answers
Reset to default 5The fetch
method on collections takes a success
parameter:
fetch
collection.fetch([options])
[...] The options hash takes
success
anderror
callbacks which will be passed (collection, response, options) and (collection, xhr, options) as arguments, respectively.
The success
callback will be called after the collection has been updated so it will be called after all the "add"
events have been triggered and dealt with. So you could do this:
collection.fetch({
success: function(collection, response, options) {
collection.trigger('fetched_and_notified');
}
});
and anyone that cares could collection.on('fetched_and_notified', ...)
to listen for such an event. If you wanted, you could provide your own fetch
implementation to trigger this event automatically, something like this:
fetch: function(options) {
options = options ? _.clone(options) : { };
var success = options.success;
options.success = function(collection, response, options) {
collection.trigger('fetched_and_notified', collection);
if(success)
success(collection, response, options);
};
Backbone.Collection.prototype.fetch.call(this, options);
}
You can trigger custom events on all kinds of objects whenever you want to based on your application using Backbone.Events
To trigger an event after rendering the view,:
var MyView = Backbone.View.extend({
initialize: function() {
_.bindAll(this);
},
render: function() {
//Do all the rendering
this.trigger('myEvent');
}
});
this.trigger('myEvent') is the line that does the trick.