2012-03-31 104 views
10

基本上我需要的是做這樣的事情如何根據模型屬性爲Backbone.js視圖動態設置className?

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函數中?

回答

14

這聽起來像模型綁定工作。

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 
    } 
2

我認爲使用this.$el.toggleClass或簡單地將該類添加到render中會容易得多。

但是如果你想要構建視圖時設置類,你可以把它作爲一個選項:

view = new App.CommentView({ 
    model: model, 
    className: model.get('parent_id') ? 'comment comment-reply' : 'comment' 
}) 
3

您應該使用屬性散列/功能:

attributes: function() { 
//GET CLASS NAME FROM MODEL 
return { 'class' : this.getClass() } 
}, 
getClass: function() { 
    return this.model.get('classname') 
} 
+0

不,這不是真的。這個「屬性」函數在_ensureElement()方法中執行,並且在那時你不能訪問this.model – 2017-10-24 16:15:21

相關問題