所以我今天第一次开始研究backbone.js。我热衷于做的一件事是将模型属性绑定到有用的控件。我的问题实际上是如何将单个模型属性绑定到控件。
我想出了一个例子,你可以将任何模型的集合绑定到一个表,选择要忽略的属性,但是我觉得我没有走正确的路。这个想法是最终扩展它并使表格像数据网格一样可编辑。我已将此添加到 JSFiddle @ http://jsfiddle.net/yqjvK/
我使用辅助函数为模型生成模板。这用于生成表头和行数据
//helper function to loop through a model's attributes choosing which to ignore
function LoopAtts(model,func,ignore){
//calls func on each unignored model attribute
}
这是我用来说明示例的基本模型
var Person = Backbone.Model.extend({
defaults: function() {
return {
firstName: "N/A",
lastName:"N/A",
score:function(){
return 0;
}
};
},
});
这是我用来打印模型的单元格数据的视图,它会监听属性何时更改,现在只需将 html 设置为更新的值。
var RowView = Backbone.View.extend({
tagName: "tr",
className: "rowView",
initialize: function() {
var cells = LoopAtts(this.model,CellTemplate,this.options.ignore);
this.listenTo(this.model, "change", this.change);
this.$el.html(_.template(cells)(this.model.attributes));
},
change:function(e){
console.log(e);
for(p in e.changed)
{
if(e.changed.hasOwnProperty(p))
{
//handle update of cell
this.$el.find("#"+p).html(this.model.attributes[p]);
}
}
}
});
这是我用来绑定到集合的视图,在将元素添加到集合时添加 rowView。
var TableView = Backbone.View.extend({
defaults: {noData:'<tr><td>No Data</td></tr>'},
tagName: "table",
firstTime: true,
initialize: function() {
this.listenTo(People, 'add', this.addOne);
this.listenTo(People, 'reset', this.addAll);
this.$el.html(this.noData);
},
addOne: function(o) {
//singleton for table data
if(this.firstTime)
{
var headers = LoopAtts(o,HeaderTemplate,this.options.ignore)
this.$el.html(_.template(headers)(o.attributes));
this.firstTime = false;
}
//assign view to model and append it to the table
var view = new RowView({model: o,ignore:this.options.ignore});
this.$el.append(view.render().el);
},
addAll: function() {
this.model.models.each(this.addOne, this);
}
})