Skip to content

Instantly share code, notes, and snippets.

@aliang
Last active December 29, 2015 16:39
Show Gist options
  • Save aliang/7698582 to your computer and use it in GitHub Desktop.
Save aliang/7698582 to your computer and use it in GitHub Desktop.
<form>
Name: <input type="text" name="name"/>
Age: <input type="text" name="age"/>
<input type="submit" value="Submit"></input>
</form>
var UserForm = Backbone.View.extend({
events: {'submit': 'save'},
initialize: function() {
_.bindAll(this, 'save');
},
save: function() {
// http://api.jquery.com/serializeArray/
var arr = this.$el.serializeArray();
// This accumulates the name/value hashes into a single hash which is much easier to submit to forms
var data = _(arr).reduce(function(acc, field) {
acc[field.name] = field.value;
return acc;
}, {});
this.model.save(data);
return false;
}
});
var userForm = new UserForm({el: this.$('form'), model: new User()});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment