Question

I have a Backbone Collection initialized by running collection.fetch() method, and then after a while, I asked the collection to fetch again in order to refresh the models. so, is there any event from Model fired that I can subscribe from View in order to remove/update the view.

Was it helpful?

Solution

There isn't a specific "the collection has been refetched" event but you don't need one. fetch resets the collection:

fetch collection.fetch([options])
[...]
When the model data returns from the server, the collection will reset.

And reset triggers a "reset" event:

reset collection.reset(models, [options])
[...]
Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end.

So just listen for "reset" events from the collection and re-render the view when you get one.


The behavior of fetch changed in Backbone 1.0, from the ChangeLog:

  • Renamed Collection's "update" to set, for parallelism with the similar model.set(), and contrast with reset. It's now the default updating mechanism after a fetch. If you'd like to continue using "reset", pass {reset: true}.

And if we look at set:

set collection.set(models, [options])

The set method performs a "smart" update of the collection with the passed list of models. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as this happens.

So you can say collection.fetch({ reset: true }) if you want to keep using the "reset" event or you can collection.fetch() and listen for individual "add", "remove", and "change" events.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top