1

I'm trying to design a load more type of system where every time you press load more you add data to the existing collection. This is a rough sketch of how the UI looks.

Everything works pretty great except as you would except everytime I re-run the

items.fetch

What it does: It overrides the entire collection with the new data

What I want it to do: I want the new records returned to be added to the records collection not override old 'records'

How can I make this work so that the newly fetched records are appended to existing records and not overridden?

user391986
  • 29,536
  • 39
  • 126
  • 205

2 Answers2

3

Add { remove: false } to your fetch call:

items.fetch({ remove: false, data: { nextId: this.info.get('nextId') } });

What's happening here is Collection#fetch will synchronize its models with the data the server returns. That includes adding new models, updating models already present, and removing models that are not included in the response.

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})

The available set options are add, remove, and merge. Setting one (or all) to false will disable that functionality in the fetch.

It sounds like you just want { remove: false }, leaving the add and merge functionality.

jridgewell
  • 1,018
  • 1
  • 8
  • 12
  • oh wow that will be amazing if it actually works for the backbone relations automatically I will try this thank you. I'm assuming this would work perfect if I was doing the fetch directly on the collection itself. Here the fetch will be on the parent relational model which has the collection as a relation. – user391986 Nov 09 '15 at 15:47
  • This is magical ... it works, although I really don't understand how since the collection is not on the actual object where i call fetch on but on a relation of itself! This is nice ty – user391986 Nov 09 '15 at 23:09
1

I'm not familiar with ,

But with a normal collection, you can do the following in parse method:

Backbone.Collection.extend({
  parse: function(response){
    // you can update the info here like this.info = response.info or similar
    return _.union(this.toJSON(), response.records);
  }
});

Basically we combine the response with existing data and return it so that we maintain the previous data when the collection updates

T J
  • 42,762
  • 13
  • 83
  • 138