我实际上绑定到表单元素上的 name 属性,因此消除了 id 和类名的使用。例如,假设我有以下模型。
User.Model = Backbone.Model.extend({
defaults: {
firstname: null,
lastname: null,
phone: null,
personemail: null
}
});
然后我创建以下助手:
// Create default binding therefore eliminating repetition
Backbone.View.prototype.createDefaultBindings = function() {
var k, v, _ref, _results;
this._bindings = {};
_ref = this.model.toJSON();
_results = [];
for (k in _ref) {
v = _ref[k];
_results.push(this._bindings['input[name="' + k +'"]'] = { observe: k });
}
return _results;
};
// Helper to overide bindings in our view
Backbone.View.prototype.mergeBindings = function() {
if (this.model) {
this.createDefaultBindings();
}
_.extend(this._bindings, this.bindings);
this.bindings = this._bindings;
};
那么我们可以有如下视图:
User.Views.Form = Backbone.View.extend({
initialize: function(options) {
this.mergeBindings();
},
render: function() {
this.stickit();
}
});
初始化我们的视图
var view = new User.Views.Form({ model: new User.Model() })
然后它将使用以下输入绑定到您的模板:
<input name="firstname" type="text">
<input name="lastname" type="text">
<input name="phone" type="text">
<input name="email" type="text">