Backbone running a method based on a collection listener

140 views Asked by At

In my application have the following code,

initialize: function() {
    Pops.Collections.TeamCollection = this.collection;
    this.collection.fetch();

    this.collection.on('sync', this.render, this);
},

render: function() {
    this.addAll();
    return this;
},

Its pretty self explanatory, fetch the collection, once it is synced with the server run the render collection. At the time of writing this sequence of code it seemed like a a good idea however it now looks like that when I save a model of the collection it runs the sync listener and runs render again. This is not the behaviour I want. Is there another listener I can use to listen for the initial fetch being complete?

1

There are 1 answers

0
Zach On BEST ANSWER

According to the backbone documentation,

Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server.

The event is essentially the "catch-all" for any CRUD operations communicating with the server, which is why it's being fired on saving a model. Looking deeper into the documentation gives clues as to how .fetch() works

When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, in which case the collection will be (efficiently) reset.

By revising your call to this.collection.fetch({reset: true}), the collection will load the data and fire a reset event that can be listened to instead of sync. This will solve your problem.