Bacbkone.js渲染中的标签名类名

bacbkone.js tagname classname in render

本文关键字:标签名 js Bacbkone      更新时间:2023-09-26

im 尝试根据模型isActive属性设置具有"非活动"或"活动"类的元素。

<tr class="inactive">

这就是我所拥有的。"非活动"是默认值。结果呈现是所有 TR 元素都具有"非活动"类

var ItemView = Backbone.View.extend({
   tagName: "tr",
   className: 'inactive',

   render : function() {
       this.className = this.model.get('Active') ? 'active' : 'inactive';
       ...

       this.$el.html( this.template(data) );
   }

});

找到一些小字

  className: function() {
     var el = this.model.get('Active') ? 'active' : 'inactive';   // Set active flag in class
     return el;
  },

但是,现在得到错误:'this.model' is undefined建议在初始化之前运行 className 函数。 IM 使用默认初始值设定项。render this.model从来没有遇到过问题。

如果您要检查模型是否处于活动状态,为什么要费心使用默认类名?在我看来,如果您在渲染函数时设置默认值,您将跳过默认值。此外,将类名添加到模板中可能更容易:

template: _.template('<tr class="<% active ? 'active' : 'inactive' %>">...</tr>');

然后,您无需担心它可能会更改的其他任何地方,并且您的代码更少。

编辑:

以下链接提供了另一种动态侦听属性更改和更新视图的方法:

如何根据 Backbone.js 视图的模型属性动态设置类名?

我使用 jquery addClass 添加了运行时类名。

  render: function() {
     var isactive = this.model.get("Active") ? "" : "inactive";
     this.$el.removeClass('inactive').addClass(isactive);

  }
相关文章: