通常创建View时是这样:
A = Backbone.View.extend({
el:'p',
className:'class',
....
});
如果这个View的new操作用在循环中,而在使用View时想根据不同的class来显示,如何动态的给className赋值?
巴扎黑2017-04-10 14:24:49
for (var i=1; i < 5; i++) {
a[i] = (function(i){
return Backbone.View.extend({
el:'p',
className:i,
....
});
})(i)
}
阿神2017-04-10 14:24:49
视图在实例化时会调用 _ensureElement 方法
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
所以第一步需要定义 tagName 这里不能定义成字符串,必须定义为函数,函数可以这样写:
tagName: function() {
var prefix = "user customize css class prefix"
return classPrefix + obj.model.get('id');
}
第二步:因为不指定 el属性时才会调用 tagName,所以根据你的需求,el 不能指定
然后你只需要写不同的css类就可以了,我写的例子函数中,css类等于classPrefix + obj.model.get('id'),所以你可以根据自己的需求定义 tagName 方法就可以了