简体   繁体   中英

Backbone.Collection firing 'reset' but not 'add'

I have a seemingly simple example that I cannot figure out. I have the latest version of Backbone, so 'add' should be automatically triggered on fetch. I have verified that fetching otherwise works correctly.

Here, event listeners are defined

var InstallerListView = Backbone.View.extend({
  $el: $('#installers-list'),
  initialize: function (args) {
    _.extend(this, args);
    this.installers.on('add', function (model) {
      // not reached
      console.log('add triggered');
    });
    this.installers.on('reset', function () {
      // reached
      console.log('reset triggered');
    });
  }
});

And here, is my fetch call

installers.fetch({
  reset: true,
  data: {/* some data */}
});

Any help getting 'add' to fire is appreciated.

When you pass in reset to your fetch call backbone suppresses all the add and remove events and fires just one reset event at the end.

From the annotated source

When you have more items than you want to add or remove individually, you can reset the entire set with a new list of models, without firing any granular add or remove events. Fires reset when finished. Useful for bulk operations and optimizations.

If necessary you could always bind to the reset event and fire the add event on each model yourself, or if you need it to fire as it adds each model you can override the reset event for your collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM