backbone.jsbackbone.js-collectionsbackbone-modelbackbone-relational

Appending new data to the Backbone Relational Relation


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?


Solution

  • 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.