Last active
December 29, 2015 16:39
-
-
Save aliang/7698582 to your computer and use it in GitHub Desktop.
Simple form example for backbone.js, from http://blog.mysema.com/2012/06/form-data-extraction-with-backbonejs.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form> | |
Name: <input type="text" name="name"/> | |
Age: <input type="text" name="age"/> | |
<input type="submit" value="Submit"></input> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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