Synchronizing the backbone.js collection with the server

I am trying to figure out how to do backbone.js. The collection remains in sync with the server at the end of the URL.

I would like to be able to add a model to the collection and the collection will automatically POST with the new model to the collection url ...

I cant the seam to find the functionality to do this anywhere.

+3


source to share


1 answer


Models are never saved to the collection endpoint, they have their own url property to customize where they are saved.

Instead of calling add

on a collection, then save

on a model, you can just call create

on a collection and it will do both, but you have to customize the url of the model.

var MyModel = Backbone.Model.extend({
    urlRoot: '/some/path'
});
var MyCollection = Backbone.Collection.extend({
    url: '/some/path',
    model: MyModel
});

var instance = new MyCollection();
instance.fetch(); //fetches at /some/path

// ...

instance.create({ foo: 'bar' }); // adds to collection and saves the new model

      



Documentation for creating

For this to work, you must set a model property for the collection.

+8


source







All Articles