I’m currently rewriting an old app with Backbone and Marionette.
In my module file 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!');
});
}
});
I am trying to hook in to the start() method because I thought this would be the normal method to use when waiting for the start() of a module. (it does get initialized only once, so I cant use the initializer. But what else?)
On the second call to spls.module(‘Insight’).start(); i recieve two “Insight started!” messages.
Why is this?
Is there a better way to solve this?
More info on what I want to achieve:
I just started using Marionette and thus don’t have deep understanding of what the modules do and in which way they interact yet.
What I wanted to achieve was basically a main App (works) which opens pages (the modules) via the router.
Currently I am calling
Spls.module('Insight').start();
From the router, but I don’t know how to design the module itself.
The initializer seems to only get called on the first .start() thus the module doesn’t know when to show it’s content.
Should I use the event aggregator like so?
// router
Spls.module('Insight').start();
Spls.vent.trigger('insight:show');
// module
Spls.vent.on('insight:show', function () { /* show index */ });
I basically need more information on how to work with modules, I could’t find any good information about the appropriate workflow regarding this.
Thanks again!
Don’t override the start method. Bad things will happen, as you’ve already seen, including your initializers won’t get run and other behind the scenes code won’t get executed.
If you need code to run when the module is started, use an initializer. If you need code to run when the module is stopped, use a finalizer. The start method and stop method take care of running the initializers, finalizers, and a handful of other necessary things behind the scenes.
As for that message showing up twice – In my quick test, I’m not seeing this message twice. I’m only seeing it once. Is there another bit of code that is defining a second module of the same name (a split module definition) or something else along those lines?
Update for your additional questions:
Calling
startmultiple times will only re-run the initializers if you have also calledstopon the module.You can keep track of which module is currently running. Then when a new route fires, you can stop the current one before starting the next one. That should be enough to things working right:
This could easily be extracted in to a method in your router or the object that your router calls if you’re using Marionette’s AppRouter.
Hope that helps.