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

时间:2012-03-31 12:53:37

标签: 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';
    }
  },

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

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

4 个答案:

答案 0 :(得分: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
  }

答案 1 :(得分:3)

您应该使用属性hash / function:

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

答案 2 :(得分:2)

我认为使用this.$el.toggleClass或只是在render内添加类会更容易。

但是,如果要在构建视图时设置类,可以将其作为选项传递:

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

答案 3 :(得分:0)

我是在View初始化时完成的

App.CommentView = Backbone.View.extend({
    initialize: function() {
        if(this.model.get("parent_id"))
            this.$el.addClass("comment-reply");
    },