I am attempting to sync an entire collection of models to the server in backbone.js. I want to POST a JSON package to the server containing all of the collection's model's attributes. This should be pretty simple but Im not sure what I am doing wrong:
var RegisterCollection = Backbone.Collection.extend({
initialize: function () {_(this).bindAll('syncCollection');},
model: RegisterModel,
url: 'api/process.php',
updateModel: function(registerModel) {
var inputName = '#'+registerModel.get('inputName');
var userInput = $(inputName).val();
registerModel.set({value: userInput});
},
syncCollection: function(registerModel) {
this.sync();
}
});
var RegisterCollectionView = Backbone.View.extend({
el: "#register",
events: {
"click #submit" : "validate"
},
validate: function(e) {
e.preventDefault();
$("#register").valid();
if ($("#register").valid() === true) {
this.updateModels();
this.collection.syncCollection();
}
},
updateModels: function (){
this.collection.forEach(this.collection.updateModel, this);;
},
initialize: function(){
this.collection.on('reset', this.addAll, this);
},
addOne: function(registerModel){
var registerView = new RegisterView({model: registerModel});
this.$el.append(registerView.render().el);
},
addAll: function(){
this.$el.empty();
this.collection.forEach(this.addOne, this);
this.$el.append('<button type="submit" class="btn-primary btn" id="submit" style="display: block;">Submit</button>');
},
render: function(){
this.addAll();
return this;
}
});
var registerCollection = new RegisterCollection();
registerCollection.fetch();
var registerCollectionView = new RegisterCollectionView({collection: registerCollection});
registerCollectionView.render();
When I try to call syncCollection(), it returns the following error: Uncaught TypeError: Object [object Object] has no method 'save'
I'm new to Backbone, so odds are that I am making a fairly elementary mistake somewhere...
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.
Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.
OK, a fresh pot of coffee and a day later, I got it. We were calling sync() improperly. Here is what we should have been doing:
syncCollection: function() {
Backbone.sync('create', this);
}
Thanks to machineghost for helping me explore this problem - I was totally focused on the wrong thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With