如何动态地为主干设置类名。基于它的模型属性的js视图?

时间:2022-01-15 06:59:50

Basically what I need is to do something like this

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

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

The problem is, that at the function passed to className is executed in context of the html of the view template, so I can't call this.model.

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

Is there any way I can access the model at this point in the rendering process? Or do I need to set the class later, for example in the render function?

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

3 个解决方案

#1


14  

This sounds like a job for model binding.

这听起来像是模型绑定的工作。

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


3  

You should use the attributes hash/function:

您应该使用属性哈希/函数:

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

#3


2  

It would be much easier I think to use this.$el.toggleClass or simply add the class inside render.

我觉得用这个会容易得多,$el。切换类或简单地在渲染中添加类。

However if you want to set the class when constructing the view, you can pass it as an option:

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

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

#1


14  

This sounds like a job for model binding.

这听起来像是模型绑定的工作。

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


3  

You should use the attributes hash/function:

您应该使用属性哈希/函数:

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

#3


2  

It would be much easier I think to use this.$el.toggleClass or simply add the class inside render.

我觉得用这个会容易得多,$el。切换类或简单地在渲染中添加类。

However if you want to set the class when constructing the view, you can pass it as an option:

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

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