【问题标题】:Best way to access a parent Module from a Sub Module with Marionette使用 Marionette 从子模块访问父模块的最佳方式
【发布时间】:2013-09-10 23:11:38
【问题描述】:

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

我可以像这样在应用程序的事件聚合器中命名事件:

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

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

但我真的不想走那条路。我认为为父模块及其子模块提供单个事件聚合器的想法更清晰。我喜欢从父级到应用程序以及子级到父级的单一接口......但也许我的想法是错误的?

我也可以像这样从 App 对象访问父模块的事件聚合器:

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

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

但我也不想那样做。我认为这会使 Child 模块和 App 耦合得太紧。

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

【问题讨论】:

  • 我没有使用事件,而是从子模块中调用了 App.Parent.something()

标签: javascript backbone.js marionette


【解决方案1】:

不幸的是,虽然 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)
});

【讨论】:

    【解决方案2】:

    您可以用子应用程序替换您的父模块。这样您就可以使用子应用事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多