Backbone-Model-Binder example
by niki4810
HTML
<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/master/backbone.js"></script>
<script src="https://raw.github.com/theironcook/Backbone.ModelBinder/master/Backbone.ModelBinder.js"></script>
<div id="viewContainer"></div>
JavaScript
$(function () {
//ideally this should come from a tempating engine such as
//handlebars
var getViewTemplate = function () {
var templateStr = '<form>';
templateStr = templateStr.concat('First Name:');
templateStr = templateStr.concat('<input type="text" name="firstName"></input>');
templateStr = templateStr.concat('<br/>LastName:');
templateStr = templateStr.concat('<input type="text" name="lastName"></input>');
templateStr = templateStr.concat('</form>');
templateStr = templateStr.concat('<button class="searchBtn">Search</button>');
return templateStr;
}
//create a backbone model and set the
//first name and last name properties as empty strings
var dataModel = new Backbone.Model();
dataModel.set({
firstName: '',
lastName: ''
});
//create a backbone view
ViewClass = Backbone.View.extend({
_modelBinder: undefined,
initialize: function () {
this._modelBinder = new Backbone.ModelBinder();
},
close: function () {
this._modelBinder.unbind();
},
events: {
"click .searchBtn": "onSearchClick"
},
onSearchClick: function () {
console.log(this.model);
},
render: function () {
var html = getViewTemplate();
this.$el.html(html);
this._modelBinder.bind(this.model, this.el);
return this;
}
});
view = new ViewClass({
model : dataModel
});
$('#viewContainer').append(view.render().$el);
});