Backbone: Set Model with Form
Backbone: Set Model with Form
by Nirvanachain
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<div class="js-container">
</div>
<script type="text/template" id="form-template">
<h1>Form</h1>
<form action="" method="Post">
<div>
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="fName" />
</div>
<button type="submit" class="js-button">Click</button>
</form>
<div>
f_Name = <%- settings.f_Name %>
<br />
l_Name = <%- settings.l_Name %>
</div>
</script>
JavaScript
var TheModel = Backbone.Model.extend({
defaults: {
f_Name: "Darth"
},
parse: function(response) {
console.log('parsing');
}
});
var TheView = Backbone.View.extend({
el: '.js-container',
initialize: function() {
this.model = new TheModel();
this.listenTo(this.model, 'change', this.render);
},
template: _.template( $('#form-template').html() ),
render: function() {
this.$el.html( this.template({settings: this.model.toJSON()}) );
return this;
},
events: {
'click .js-button': 'onSubmit'
},
onSubmit: function(e) {
e.preventDefault();
console.log( this.model.toJSON() );
this.model.set('l_Name', 'Vader');
console.log( this.model.toJSON() );
return this;
}
});
var theView = new TheView();
theView.render();