我有一个带有几个子模块的牵线木偶模块。父模块具有自己的事件聚合器,我想在子模块中使用它来触发事件。我知道我可以使用应用程序的事件聚合器,但是这些事件特定于父模块及其子级,而不是整个应用程序。

我可以在应用程序的事件聚合器中为事件命名空间,如下所示:

App.module("Parent.Child", function(self, App, ...) {

  // somewhere in the child
  App.vent.trigger("Parent:something");
});

但是我真的不想走那条路。我认为为“父模块”及其子级创建单个事件聚合器的想法比较干净。我喜欢从父级到应用程序,从子级到父级只有一个接口(interface)……但是,也许我在这个想法上错了?

我还可以从App对象访问父模块的事件聚合器,如下所示:
App.module("Parent.Child", function(self, App, ...) {

  // somewhere in the child...
  App.Parent.vent.trigger("something");
});

但是我也不想这样做。我认为这会使Child模块和App紧密结合在一起。

还有其他想法或选择吗?也许这些是好主意,但我只是不明白这样做的好处。

最佳答案

不幸的是,虽然Marionette允许您通过submodules属性向下钻取应用程序/模块/子模块链,但它并不能轻松地访问以标识Module的父级。我们曾几次遇到过这种情况可能会有所帮助,但从未遇到没有成为问题的情况。就是说,如果您认为这可以使您的代码库更整洁,则可以尝试包装_addModuleDefinition函数来创建parent属性:

var func = Marionette.Module._addModuleDefinition;
Marionette.Module._addModuleDefinition = function(parentModule, module) {
    module.parent = parentModule;
    func.apply(this, arguments);
};

这将使您能够执行类似的操作
App.module("Parent.Child", function(self, App, ...) {
    self.parent.trigger('whatever'); // (vent isn't required anymore)
});

关于javascript - 使用 Marionette 从子模块访问父模块的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18730191/

10-11 23:57
查看更多