[英]How can I dynamically set a className for a Backbone.js view based on it's model attributes?
Basically what I need is to do something like this 基本上我需要的是做这样的事情
App.CommentView = Backbone.View.extend({
className: function() {
if (this.model.get('parent_id')) {
return 'comment comment-reply';
} else {
return 'comment';
}
},
The problem is, that at the function passed to className
is executed in context of the html of the view template, so I can't call this.model
. 问题是,传递给className
的函数是在视图模板的html的上下文中执行的,所以我不能调用this.model
。
Is there any way I can access the model at this point in the rendering process? 有没有什么办法可以在渲染过程中访问模型? Or do I need to set the class later, for example in the render
function? 或者我需要稍后设置类,例如在render
函数中?
This sounds like a job for model binding. 这听起来像是模型绑定的工作。
App.CommentView = Backbone.View.extend({
initialize: function () {
// anytime the model's name attribute changes
this.listenTo(this.model, 'change:name', function (name) {
if (name === 'hi') {
this.$el.addClass('hi');
} else if......
});
},
render: function () {
// do initial dynamic class set here
}
You should use the attributes hash/function: 你应该使用属性hash / function:
attributes: function () {
//GET CLASS NAME FROM MODEL
return { 'class' : this.getClass() }
},
getClass: function() {
return this.model.get('classname')
}
It would be much easier I think to use this.$el.toggleClass
or simply add the class inside render
. 我认为使用它会更容易this.$el.toggleClass
或只是在render
添加类。
However if you want to set the class when constructing the view, you can pass it as an option: 但是,如果要在构造视图时设置类,可以将其作为选项传递:
view = new App.CommentView({
model: model,
className: model.get('parent_id') ? 'comment comment-reply' : 'comment'
})
I did it at View initialize 我在View初始化时做到了
App.CommentView = Backbone.View.extend({
initialize: function() {
if(this.model.get("parent_id"))
this.$el.addClass("comment-reply");
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.