2012-03-31 66 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

相关问题