Reputation: 1482
I'm trying to see if there is a way to automatically bind an start
,stop
,before:start
event to all modules that are initialized without having to add this.on('start',function() {})
boilerplate to every module.
I'm just doing some basic logging / debugging via these functions to help me understand my infrastructure a bit better and it would be cool if I could define events similar to how overriding a prototype is overridden.
Example of the type of "boilerplate" I'm having to add to accomplish such a seemingly simple task. Obviously this is in coffee...
@on "before:start", ->
console.log "starting: #{Self.moduleName}"
return
@on "start", (defaults)->
_init()
console.log "started: #{Self.moduleName}"
return
@on "stop", () ->
console.log "stopped: #{Self.moduleName}"
return
_init = () ->
return
My first thought was to override the MyApp.module()
function somehow and put the event bindings in there? Not sure how I would do that though... :-/
How would one accomplish this?
Upvotes: 0
Views: 438
Reputation: 8293
I would do as you said.
You could override the constructor. But if you do that, you'll have to be really careful, and rebind any static method and the prototype that were bound to it. Basically, you could do something like that:
var module = Marionette.Module;
Marionette.Module = function() {
// this would be bound BEFORE anything else happens
this.on('before:start', ...);
module.apply(this, arguments);
// this would be bound AFTER anything else happens
this.on('before:start', ...);
};
Then again, you'd have to rebind the prototype and the static methods afterward.
Edit:
About the rebindings:
// save the prototype and any static method (or value)
var protoProps = Marionette.Module.prototype;
// this is maybe only the extend function
var staticProps = {};
for(var prop in Marionette.Module) staticProps[prop] = Marionette.Module[prop];
// override the Module
var module = Marionette.Module;
Marionette.Module = function() {
...
};
// rebind
Marionette.Module.prototype = protoProps;
_.extend(Marionette.Module, staticProps);
Upvotes: 1