Backbone.js 视图呈现:是否有更好的方法来控制视图元素的类名?
这是我想要的功能,但它不起作用。我不确定类名何时确定,但被调用方只是元素本身;在这种情况下,它将是。有没有一种方法可以让className访问模型Backbone.js 视图呈现:是否有更好的方法来控制视图元素的类名?,backbone.js,Backbone.js,这是我想要的功能,但它不起作用。我不确定类名何时确定,但被调用方只是元素本身;在这种情况下,它将是。有没有一种方法可以让className访问模型 目前,我可以在模板中放置另一个div来控制该类,但如果我能够从视图本身控制类名,则肯定不需要该div。如果是我,我可能会在render use a helper函数中设置该类类型: var myView = Backbone.View.extend({ tagName: 'div', className: function() {
目前,我可以在模板中放置另一个div来控制该类,但如果我能够从视图本身控制类名,则肯定不需要该div。如果是我,我可能会在render use a helper函数中设置该类类型:
var myView = Backbone.View.extend({
tagName: 'div',
className: function() {
return this.model.isNew() ? 'new' : 'old';
}
如果需要,您可以稍后在事件处理程序中重用applyClass:
var myView = Backbone.View.extend({
render: function() {
this.applyClass();
return this;
},
applyClass: function() {
var isNew = this.model.isNew();
$(this.el)
.toggleClass('new', isNew)
.toggleClass('old', !isNew);
}
});
如果是我,我可能会在render中使用一个helper函数设置该类型的类:
var myView = Backbone.View.extend({
tagName: 'div',
className: function() {
return this.model.isNew() ? 'new' : 'old';
}
如果需要,您可以稍后在事件处理程序中重用applyClass:
var myView = Backbone.View.extend({
render: function() {
this.applyClass();
return this;
},
applyClass: function() {
var isNew = this.model.isNew();
$(this.el)
.toggleClass('new', isNew)
.toggleClass('old', !isNew);
}
});
您需要在initialize方法中使用u.bindAll来设置className函数的上下文
initialize: function(options) {
this.model.bind('change', this.applyClass, this);
}
您需要在initialize方法中使用u.bindAll来设置className函数的上下文
initialize: function(options) {
this.model.bind('change', this.applyClass, this);
}
或者,您可以避免使用className属性并使用attributes函数
var myView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'className');
},
tagName: 'div',
className: function() {
return this.model.isNew() ? 'new' : 'old';
}
});
或者,您可以避免使用className属性并使用attributes函数
var myView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'className');
},
tagName: 'div',
className: function() {
return this.model.isNew() ? 'new' : 'old';
}
});
您可能也希望对applyClass使用更好的名称,因为它有点通用。适合您的环境的东西。您可能也想为applyClass使用一个更好的名称,它有点通用。适合你的环境。酷!但是,导致这种方法不起作用的原因是元素已经在make中创建,并且在调用initialize方法之前已经调用了unbound className函数。酷!但是,导致这种方法不起作用的原因是元素已经在make中创建,并且在调用initialize方法之前已经调用了unbound className函数。