如何根据它的模型属性为Backbone.js视图动态设置className?

Jak*_*old 10 javascript backbone.js backbone-views

基本上我需要的是做这样的事情

App.CommentView = Backbone.View.extend({
  className: function() {
    if (this.model.get('parent_id')) {
      return 'comment comment-reply';
    } else {
     return 'comment';
    }
  },
Run Code Online (Sandbox Code Playgroud)

问题是,传递给的函数className是在视图模板的html的上下文中执行的,所以我无法调用this.model.

有没有什么办法可以在渲染过程中访问模型?或者我是否需要稍后设置该类,例如在render函数中?

Tre*_*vor 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
  }
Run Code Online (Sandbox Code Playgroud)