我可以直接调用行为方法而不使用eventproxy吗?

时间:2017-01-03 08:55:28

标签: javascript backbone.js marionette behavior backbone-events

我正在寻找其他方法来从视图中调用Marionette behaviors中定义的方法。

肯定有 eventproxy ,但是直接调用该方法可能更直观,如:

view.behaviorsMethod();

我可以分配,如:

view.method = behavior.method;

我可以检查重新分配,因为它可能会导致其他人意外结果:

view.method = (view.method !== undefined ? view.method : behavior.method);

但这似乎并不是一种优雅的方式。

1 个答案:

答案 0 :(得分:0)

你的问题的答案是你不能直接这样做,但总会有一种方法。 你可以使用_.invoke(this._behaviors, 'yourMethodName')来做,但我不鼓励使用它 从那以后

  1. _behaviors是Marionette.View类的私有变量,它的名称可以更改,也可以在即将发布的版本中删除

  2. 您必须为方法设置上下文,因为_.invoke不会设置 适当的方法的背景。

  3. 如果您可以正确设置上下文,那么这将适合您。

    正如@ThePaxBisonica在评论中所建议的那样 我建议你使用mixin模式,你可以从中扩展你的行为和视图,你不必设置任何上下文,也不必担心_behavior私有变量

    作为

    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
    }))
    

    希望它有所帮助。 我知道这有点长的方法。

相关问题