我正在寻找调用 Marionette 的 behaviors 中定义的方法的替代方法。从 View 内部。
肯定有eventproxy 但也许直接调用该方法更直观,例如:
view.behaviorsMethod();
我可以分配它,例如:
view.method = behavior.method;
我可以检查重新分配,因为这可能会给其他人带来意想不到的结果:
view.method = (view.method !== undefined ? view.method : behavior.method);
但这似乎不是一个优雅的方式。
最佳答案
你的问题的答案是你不能直接这样做,但总有办法。
你可以使用 _.invoke(this._behaviors, 'yourMethodName')
但我不鼓励使用它
自从
_behaviors 是 Marionette.View 类的私有(private)变量,它的名称可以更改,也可以在即将推出的版本中删除
您必须为该方法设置上下文,因为 _.invoke 不会设置 纠正此问题的方法的上下文。
如果您可以正确设置上下文,那么这对您有用。
按照 @ThePaxBisonica 在评论中的建议 我建议您使用混合模式,您可以从中扩展您的行为和 View ,并且您不必设置任何上下文,也不必担心 _behavior 私有(private)变量
作为
var mixin = {
behaviorMethodWhichYouWantToCallFromView: function(){
alert("mixin method");
}
}
var behavior = mn.behavior.extend(_.extend(mixin, {
//actual behavior code remove the method as behavior will get it from mixin
}))
var view = mn.view.extend(_.extend(mixin, {
//actual view code remove the method as behavior will get it from mixin
}))
希望有帮助。 我知道这个方法有点长。
关于javascript - 我可以不使用 eventproxy 直接调用行为方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439697/