Module.start()已激发两次

Module.start() fired twice?

本文关键字:两次 start Module      更新时间:2023-09-26

我目前正在用Backbone和Marionette重写一个旧应用程序。在我的模块文件spls.module.insight.js:中

spls.module('Insight', {
    startWithApp: false,
    define: function(self, spls, Backbone, Marionette, $, _) {
        self.start = function () {
            console.log('Insight started!');
        }
        self.addInitializer(function() {
           console.log('Insight instantiated!');
        });
    }
});

我试图挂接start()方法,因为我认为这将是在等待模块的start()时使用的正常方法。(它只初始化过一次,所以我不能使用初始化器。但还有什么?)在对spls.module('Insight').start()的第二次调用中;我收到两条"洞察开始了!"的信息。为什么会这样?

有更好的方法来解决这个问题吗?


关于我想要实现的目标的更多信息:我刚开始使用Marionette,因此还没有深入了解模块的功能以及它们的交互方式。我想要实现的基本上是一个通过路由器打开页面(模块)的主应用程序。目前我正在呼叫

Spls.module('Insight').start();

来自路由器,但我不知道如何设计模块本身。初始化器似乎只在第一个.start()上被调用,因此模块不知道何时显示其内容。我应该这样使用事件聚合器吗?

// router
Spls.module('Insight').start();
Spls.vent.trigger('insight:show');
// module
Spls.vent.on('insight:show', function () {  /* show index */ });

我基本上需要更多关于如何使用模块的信息,我找不到任何关于这方面适当工作流程的好信息。

再次感谢!

不要重写启动方法。正如您已经看到的,糟糕的事情会发生,包括初始化程序无法运行,其他幕后代码无法执行。

如果您需要在模块启动时运行代码,请使用初始值设定项。如果您需要在模块停止时运行代码,请使用终结器。start方法和stop方法负责在后台运行初始化器、终结器和其他一些必要的东西。

至于这条消息出现两次——在我的快速测试中,我没有看到这条消息两次。我只见过一次。是否还有另一段代码正在定义第二个同名模块(拆分模块定义)或其他类似的代码?


更新您的其他问题:

如果您还在模块上调用了stop,那么多次调用start只会重新运行初始化程序。


Spls.module("Insight").start();
// some time later...
Spls.module("Insight").stop();
// now it can be re-started and the initializers will run again
Spls.module("Insight").start();

您可以跟踪当前正在运行的模块。然后,当一条新路线启动时,您可以在启动下一条路线之前停止当前路线。这应该足以让事情正常运转:


insightRoute: function(){
  if (this.module){
    this.module.stop();
  }
  this.module = Spls.module("Insight");
  this.module.start();
}

如果你使用的是Marionette的AppRouter,这可以很容易地提取到路由器中的方法或路由器调用的对象中。

希望能有所帮助。