[英]How can I dynamically set a className for a Backbone.js view based on it's model attributes?
基本上我需要的是做這樣的事情
App.CommentView = Backbone.View.extend({
className: function() {
if (this.model.get('parent_id')) {
return 'comment comment-reply';
} else {
return 'comment';
}
},
問題是,傳遞給className
的函數是在視圖模板的html的上下文中執行的,所以我不能調用this.model
。
有沒有什么辦法可以在渲染過程中訪問模型? 或者我需要稍后設置類,例如在render
函數中?
這聽起來像是模型綁定的工作。
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
}
你應該使用屬性hash / function:
attributes: function () {
//GET CLASS NAME FROM MODEL
return { 'class' : this.getClass() }
},
getClass: function() {
return this.model.get('classname')
}
我認為使用它會更容易this.$el.toggleClass
或只是在render
添加類。
但是,如果要在構造視圖時設置類,可以將其作為選項傳遞:
view = new App.CommentView({
model: model,
className: model.get('parent_id') ? 'comment comment-reply' : 'comment'
})
我在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.