Andrew
Andrew

Reputation: 6394

Backbone.js: fetch({add: true}), trigger change event?

I am wondering if there is any way to get the changed models when passing the add: true to fetch. It renders all the new models in the collection but I'd like to also know if there is any models that changed.

Is this possible?

I also considered the possibility of passing a different function as the success handler to fetch, a function that will re-render only certain portions of the view and not the entire view.

Upvotes: 0

Views: 2814

Answers (3)

aapierce
aapierce

Reputation: 897

As of version 0.9.10, you should use {update:true} instead of {add:true}. This will tell the collection to trigger a change event for each one of its models that has changed. (Note that the change event is triggered on the collection not the models)

If you want the collection to add and update models, but not remove them, you can accomplish this like so:

myCollection.fetch({update:true, remove:false});

Here's the relevant section in the Backbone.js documentation.

Upvotes: 2

ggozad
ggozad

Reputation: 13105

The usual pattern is to have a view that renders your models. You then:

  • subscribe in the collection's view to the collection's add event in order to append the views of the added models.
  • let your models' views subscribe to the model's change to re-render.

If you still want to have only one view, you: - subscribe to the collection's add event in order to append to the view. - subscribe to the collection's change event and update parts of the view.

Upvotes: 2

TYRONEMICHAEL
TYRONEMICHAEL

Reputation: 4244

You can bind to the "add" event and trigger a method that only updates a portion of the view. You have to explicitly bind a collections events in order to re-render your view. So in other words you control which parts of the view should be rendered. Can you not just alter the function where you are rendering you view based on the collection "change" event?

Each model has a method isNew(), and hasChanged(). You could loop through your collection to see which models have changed. If there is an easier and more proficient way to do this, I am all ears.

Maybe you can post some code so we can see exactly what you are doing?

Upvotes: 1

Related Questions