Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does backbone trigger .add when a collection is .fetched?

Tags:

backbone.js

I am converting my backbone app so that it starts communicating with the server, previously I had just been populating the collection with test data using .add()

I have tied some events to the collections add event. So every time an item is added to the collection I can render the view and update some statistics.

it appears that as soon as i add the .fetch() call to get data from the server the add events stop.

for example

var PayableCommitmentCollection = Backbone.Collection.extend({
    model:PayableCommitment,
    url:"/cc/account/contributions/",

    initialize: function() {
        this.bind("add",this.setInitialAmount,this);
    }
 }

this.SetInitialAmount() is never called after fetch creates the models in the collection.

I also have 2 views that are watching for items to be added to this collection that are now not updating.

My obvious work around is to write my own AJAX call so that I can add the items the same way I have been during development so far, however I'm sure backbone has the smarts to help me out here.

Can anyone suggest a way i can bind to the completion of fetch, or to make it stimulate the add event.

like image 960
Bluephlame Avatar asked Aug 05 '12 04:08

Bluephlame


2 Answers

The fetch method accepts a hash of options. One of these options can be the "add" option, which calls add on the collection instead of reset.

collection.fetch({ add: true });
like image 54
Darren Fung Avatar answered Jan 03 '23 10:01

Darren Fung


From the fine manual:

fetch collection.fetch([options])

Fetch the default set of models for this collection from the server, resetting the collection when they arrive.

And a reset:

reset collection.reset(models, [options])

Adding and removing models one at a time is all well and good, but sometimes you have so many models to change that you'd rather just update the collection in bulk. Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end.

So a fetch will trigger a single "reset" event rather than a bunch of "add" events. You need a collection-wide version of setInitialAmount that you can bind to "reset".


In Backbone 1.0, Collection#fetch has this to say:

fetch collection.fetch([options])

Fetch the default set of models for this collection from the server, setting them on the collection when they arrive.
[...]
The behavior of fetch can be customized by using the available set options. For example, to fetch a collection, getting an "add" event for every new model, and a "change" event for every changed existing model, without removing anything: collection.fetch({remove: false})

So, if you're using 1.0+ then all you need to do is call your fetch with the remove: false option.

like image 37
mu is too short Avatar answered Jan 03 '23 11:01

mu is too short