Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用木偶从子模块访问父模块的最佳方式_Javascript_Backbone.js_Marionette - Fatal编程技术网

Javascript 使用木偶从子模块访问父模块的最佳方式

Javascript 使用木偶从子模块访问父模块的最佳方式,javascript,backbone.js,marionette,Javascript,Backbone.js,Marionette,我有一个木偶模块和几个子模块。父模块有自己的事件聚合器,我想在子模块中使用它来触发事件。我知道我可以使用应用程序的事件聚合器,但这些事件特定于父模块及其子模块,而不是整个应用程序 我可以在应用程序的事件聚合器中为事件命名名称空间,如下所示: App.module("Parent.Child", function(self, App, ...) { // somewhere in the child App.vent.trigger("Parent:something"); }); 但

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

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

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");
});
但我也不想那样做。我认为这会将子模块和应用程序耦合得太紧


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

不幸的是,虽然木偶网让您能够通过
子模块属性深入查看应用程序/模块/子模块链,但它不能轻松识别
模块的父模块。我们曾经遇到过几次这样做可能会有所帮助的情况,但从未遇到过这样的情况:没有这样做就成了一个问题。也就是说,如果您认为这会使您的代码库更干净,您可以尝试包装
\u addModuleDefinition
函数来创建
父属性

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

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

而不是使用事件,我只是从子模块调用了App.Parent.something()