【问题标题】:How can I dynamically set a className for a Backbone.js view based on it's model attributes?如何根据模型属性为 Backbone.js 视图动态设置类名?
【发布时间】:2012-03-31 12:53:36
【问题描述】:

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

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 函数中?

【问题讨论】:

    标签: javascript backbone.js backbone-views


    【解决方案1】:

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

    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】:

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

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

      【讨论】:

      • 不,这不是真的。该“属性”函数在 _ensureElement() 方法中执行,此时您无权访问 this.model
      【解决方案3】:

      我认为使用this.$el.toggleClass 或简单地在render 中添加类会容易得多。

      但是如果你想在构造视图的时候设置类,你可以把它作为一个选项传递:

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

      【讨论】:

        【解决方案4】:

        我是在视图初始化时完成的

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-09
          • 1970-01-01
          • 2014-12-10
          • 1970-01-01
          • 1970-01-01
          • 2013-10-20
          • 2012-08-21
          • 1970-01-01
          相关资源
          最近更新 更多