twinlakes
twinlakes

Reputation: 10218

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.

Upvotes: 1

Views: 114

Answers (1)

Jack
Jack

Reputation: 10993

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.

Upvotes: 1

Related Questions