Reputation: 12977
I have a collection of users (model user) model has a boolean value: isExport i have a button that on click supposed to post to the server all the users that isExport=true Can anyone suggest a suitable solution for this problem?
I know it's possible to wrap the collection as a model and overwrite the toJSON function but couldn't manage it so far (can someone please give a code example?)
App.User = Backbone.Model.extend({ defaults: {isExport: false}...});
App.Users = Backbone.Collections.extend({model: App.User...});
Thanks! Roy
Upvotes: 0
Views: 130
Reputation: 12977
App.Views.ExportAll = Backbone.View.extend({
el: '#exportAll',
events: {
'click': 'exportAll'
},
exportAll: function(e){
e.preventDefault();
console.log('exporting all');
console.log(this.collection.toJSON());
var exportModel = new App.Models.Export;
exportModel.set("data", this.collection.toJSON());
console.log(exportModel.toJSON());
exportModel.save();
}
});
I think this is the best solution for the problem
Upvotes: 0
Reputation: 1141
Backbone comes with RESTful support. So, if you give each collection a url pointing to the collection rest service, then with a few functions (create,save) you can handle server requests.
App.Models.User = Backbone.Model.extend();
App.Collections.Users = Backbone.Collection.extend({
url: 'users',
model: App.Models.User
});
So, this way, you can:
var users = new App.Collections.Users();
users.fetch(); // This will call yoursite.com/users
// Expecting a json request
And then you can:
users.create({ name: 'John', isExport: true });
This will send a post request to the server, in order to create a new record. And you can check on server side if it has the flag you want.
Upvotes: 0
Reputation: 146164
Backbone collections by default don't have any write operations to the server, so you'll need to add a new method to your Collection subclass such as doExport
, use .where
to get the models with isExport=true
and their toJSON()
to get an array of objects which you can then send to the server with Backbone.sync
or $.post
.
Upvotes: 1