簡體   English   中英

如何根據它的模型屬性為Backbone.js視圖動態設置className?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM