简体   繁体   中英

Backbone Collection and Model url, bulk model collection save

I want to achieve.

1. Creating a single model on model.save should point to url mentioned in Models attributes

2. I want to do a bulk save ( how can i do that ). So, as per example, say I have arrays of books model and I want to save it at once using Collection's url.

var BookModel = Backbone.Model.extend({
   idAttribute: 'id',
   url: function() {
     return 'http:/test.com/books/addsinglebook'
   },
   defaults: {
     id: null,
     name: ''
  },
});

var BookCollection = Backbone.Collection.extend({
  url: 'http:/test.com/books/addbulkbooks',
  model: BookModel,   
});

// bookmodel.save() should point to /addsinglebook
// bookcollection.somesavemethod() should point to /addbulkbooks

Since Backbone collection doesn't have a save and create is for a single model, do I need to add my own method to the prototype for implementing a bulk save?

1. Use urlRoot

var BookModel = Backbone.Model.extend({
   idAttribute: 'id',
   urlRoot: 'http:/test.com/books/addsinglebook',
   defaults: {
     id: null,
     name: ''
  },
});

2. Your should implement your own save and create , cause backbone supports basic RESTfull API, which on in it's order doesn't support bulk update/create. Look here and here for similar solutions.

Yes, you need to add your own method to the Collection's class for implementing a bulk save. There you can use Underscore's each method to iterate through models of the Collection:

var BookCollection = Backbone.Collection.extend({
...
    bulkSave: function() {
        this.each(model.save);
    }
...

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