Backbone.js - How to save model by form and post to server

Carlos Azaustre picture Carlos Azaustre · Apr 30, 2013 · Viewed 19.4k times · Source

I'm n00b in BackboneJS/RequireJS and I'm developing an web app that use a RESTful API. So I've a model like this:

models/pet.js

define([
  'backbone'
], function(Backbone){

var PetModel = Backbone.Model.extend({

    urlRoot: 'http://localhost:3000/pet',
    idAttribute: '_id',

    defaults: {
        petId: "",
        type: "",
        name: "",
        picture: "",
        description: "",
        breed: "",
        size: "",
        sex: "",
        age: "",
        adopted: false,
    }
});

  return PetModel;
});

a collection: collections/pets.js

define([
  'backbone',
  'models/pet'
], function(Backbone, PetModel){

    var PetsCollection = Backbone.Collection.extend({
    url: 'http://localhost:3000/pets',
    model: PetModel,
});

  return PetsCollection;
});

And a view that renders a form to add new models (Maybe it's possible another way more elegant) views/petAddNew.js

define([
  'jquery',
  'backbone',
  'models/pet',
  'collections/pets',
  'text!templates/pet/addNew.html'
], function($, Backbone, PetModel, PetsCollection, petAddNewTemplate){

var PetAddNewView = Backbone.View.extend({

    el: $('#formAdd'),
    template: _.template(petAddNewTemplate),

    events: {
        'click #add'        : 'submitAdd',
    },

    initialize: function() {
        this.model = new PetModel();
        this.collection = new PetsCollection();
        _.bindAll(this, 'submitAdd');
    },

    render: function() {
        var view = this;
        view.$el.html( view.template );
        return view;
    },


    submitAdd: function(e) {
        //Save Animal model to server data
        e.preventDefault();
        var pet_data = JSON.stringify( this.getFormData( this.$el.find('form') ) );
        this.model.save(pet_data);
        this.collection.add(this.model);
        return false    
    },

    //Auxiliar function
    getFormData: function(form) { 
        var unindexed_array = form.serializeArray();
        var indexed_array = {};

        $.map(unindexed_array, function(n, i){
            indexed_array[n['name']] = n['value'];
        });

        return indexed_array;
    },

});

return PetAddNewView;
});

So when I submit the form I don't post any data to server. I don't know how to fix it. Any ideas? Thanks in advance!

Answer

Sai Chaithanya picture Sai Chaithanya · May 3, 2013

You need set the attributes first and then save.

//Auxiliar function
getFormData: function(form) { 
    var self = this;
    var unindexed_array = form.serializeArray();

    $.map(unindexed_array, function(n, i){
        self.model.set({
            n['name']: n['value']
        });
    });
}

Now this.model.save() works (saving on the server side).

You can see it work in a fiddle.