2017-01-03 34 views
1

我正在尋找替代方法來從視圖內調用Marionette's behaviors中定義的方法。我可以直接調用行爲方法而不使用eventproxy嗎?

可以肯定存在eventproxy,但也許它更直觀地調用該方法直接,如:

view.behaviorsMethod(); 

我可以分配它想:

view.method = behavior.method; 

我可以檢查重新分配,因爲它可能會導致其他人意想不到的結果:

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

但這似乎並不是一種優雅的方式。

+0

你有權訪問行爲中的視圖,如果你想這樣做,你可以從那裏擴展視圖。 –

回答

0

你的問題的答案是你不能直接這樣做,但總有一種方法。 你可以做到這一點使用_.invoke(this._behaviors, 'yourMethodName')但我會勸阻使用它 因爲

  1. _behaviors是Marionette.View類的私有變量,它的名稱可以更改,也可以在即將到來的版本中被刪除

  2. 您將不得不爲該方法設置上下文,因爲_.invoke不會將該方法的上下文設置爲適當的方式 。

如果您可以正確設置上下文,那麼這將適用於您。

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

希望它能幫助。 我知道這是有點長途徑。

+0

Thx概述了方法!我會和隊友討論這個問題,也許我們會試試mixin,而不是build-in-event-proxy :) –

相關問題