简体   繁体   中英

backbone.js collection sync with server

I'm trying to figure out how to make a backbone.js Collection stay synchronized with a server at the end of an url.

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

I cant seam to find the functionality for this anywhere.

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

Instead of calling add on the collection then save on the model, you can just call create on the collection and it'll do both, but you must configure the model's URL.

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 create

In order for this to work, you should set the model property of the collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM