如何使用变量作为选项向我的视图添加行为? 在我的例子中,我想要使用的变量是视图的一个选项,但是,当我尝试这个时:
behaviors: {
prodMessage: {
profile: this.options.userdata.attributes._userid
}
},
我明白了:
Uncaught TypeError: Cannot read property 'attributes' of undefined
我认为这是因为这发生在建筑而不是启动。
那么,您有解决方法吗?
答案 0 :(得分:1)
您的版本中的代码会在应用程序加载期间执行。所以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);
}
});