user888734
user888734

Reputation: 3897

Combine backbone collection / javascript objects with new models from the server

I have a collection of locations on a google map object, stored in a Backbone collection:

var Location = Backbone.Model.extend({
    defaults: {
        latitute: "",
        longitude: "",
        visited: false;
    },
});

var LocationCollection = Backbone.Collection.extend({
    model: Location,
    url: 'api/locations'
});

As each point is clicked on the map, the location model property 'visited' is set to true.

The original collection of locations comes from the database (based on the bounds of the map), which does not store any 'visited' information, simply a list of locations within range.

When the user changes the bounds of the Google map, by moving around, zooming in/out etc, I need to retrieve a brand new list of locations within the new parameters, then somehow assimilate this list with the existing collection, adding new locations, but retaining the visited properties for existing ones?

I hope this isn't too vague, but where to start?? Is there a way with jQuery to map complex objects from one collection to another? Or would it make more sense to split the collections, sending visited information back to the server and combine them there? Or will the Backbone collection remember 'visited' values and only update those in the collection with new properties?

Sorry, I thought I knew this stuff, but I have never ever done anything like this.

Upvotes: 3

Views: 431

Answers (1)

jmk2142
jmk2142

Reputation: 8581

It's possible. Basically, I'm assuming the following. The user has a bunch of locations. They click and the location attribute changes to visited = true;

When they zoom out, you fetch() new models that are now in view but you also want don't want those old locations to reset to visited = false; Server will basically calculate the dimensions of the view and provide a bunch of location models.

If this is what you want, all you need to do is make a fetch() call with the options: add:true.

collection.fetch({
    add: true
});

When you pass the add:true option to your fetch() call, it won't reset the collection (thereby wiping your visited data). Instead, it will only add models that don't already exist in the collection. So if you already have locations.id = 1, 2, 3 and your server returns locations.id = 1, 2, 3, 4, 5, 6 ... only 4, 5, 6 will be added to your already existing collection. The visited = true (or false) data of 1, 2, 3 should remain intact.

Upvotes: 2

Related Questions