Marionette 行为:添加动态选项

Marionette Behaviors: Add dynamic options

如何将变量作为选项添加到我的视图中? 在我的例子中,我想使用的变量是视图的一个选项,但是,当我尝试这个时:

behaviors: {
    prodMessage: {
        profile: this.options.userdata.attributes._userid
    }
},

我得到:

Uncaught TypeError: Cannot read property 'attributes' of undefined

我认为这是因为这发生在构建而不是初始化中。

那么,您有什么解决方法可以实现这一目标吗?

您的版本中的代码在应用程序加载期间执行。所以 this 实际上并不指向视图实例,而是可能指向 window 对象。要让 this 指向视图,您需要延迟行为规范,以便在构造视图实例时执行它:

``

behaviors: function() {
  return {
    prodMessage: {
      profile: this.options.userdata.attributes._userid
    }
  };
}

``

查看此 codepen 以获得完整版本。


另一种选择是让行为通过 this.view:

访问视图
prodMessage = Marionette.Behavior.extend({
  onShow: function() {
    alert(this.view.options.userdata.attributes._userid);
  }
});