最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can an event be triggered in Backbone once a collection has been fetched and rendered? - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

The fetch method on collections takes a success parameter:

fetch collection.fetch([options])

[...] The options hash takes success and error 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论