Shawn Mclean
Shawn Mclean

Reputation: 57469

Backbone.js events from .create and serialize a form

I'm using backbone.js to know when I try to submit a form. In this event, I cant use this. So I'm hoping to use the argument to serialize the form contents to json.

How do I do this?

window.UserView = Backbone.View.extend({
    el: 'body',
    model: new window.UserList,
    template: _.template($('#user-view-template').html()),
    events: { "submit form#newUser": "addItem" },
    initialize: function () {
        _.bindAll(this, 'render', 'update', 'addItem');
        this.model.bind('refresh', this.render);
        this.update();
    },
    render: function () {
        $("#listContainer").html(this.template({ users: this.model.toJSON() }));
        return this;
    },
    update: function () {
        this.model.fetch();
    },
    addItem: function (e) {
        e.preventDefault();
        var person_attrs = $(e.target).serializeObject();
        this.model.create(person_attrs, {
            success: function (saved_person, data) {
                if (data.Result == "Success") {
                    alert("success, new Id: " + data.Model.Id);
                }
                else {
                    //Need to remove the model from the collection
                    alert(data.Message);
                }
            },
            error: function (aborted_person, response) {
                alert("Server Error");
            }
        });
        return false;
    }
});

So far, I got the form to serialize and send to the server. Is this the right way to do that?

I also have a few other problems:

  1. Remove or cancel the local create model if the server returned an error.
  2. If the server result is "Success", I'd like to assign the returned Id to the model.
  3. Refresh the view. I thought the event refresh would be called after the server returned.

Upvotes: 0

Views: 4814

Answers (1)

Bill Eisenhauer
Bill Eisenhauer

Reputation: 6183

I'd be interested in why you cannot use 'this' in your function. If you've registered your submit event within your view, you might have something that looks like this:

events: {
  "submit form": "onSubmit"
},

where the DOM event will be wired to the onSubmit function. The onSubmit function might look like this:

onSubmit: function(e) {
  e.preventDefault();
  var attrs = this.serialize();
  if (this.model.set(attrs)) {
    // Do something here.
  }
},

serialize: function() {
  return {
    message: $("textarea[name='message']").val()
  };
}

where you could use JQuery selectors in your serialize method to acquire the attributes and then set them in your model before saving it. You could also just save it if desired. There may be more elegant ways to get the form data, but this is the technique I always use.

Upvotes: 3

Related Questions