Search code examples
jquerybackbone.js

Sync an entire collection of models in backbone.js


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...


Solution

  • 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.