I'm looking for an elegant way to build an event-driven architecture where modules (scripts) are completely independent and decoupled from each other and rely only on Mediator for communication. Let's consider typical example:
var SomeModule = function () {...};
SomeModule.init = function ()
{
Mediator.register ('SomeEvent', this.onSomeEvent, this);
Mediator.register ('OtherEvent', this.onOtherEvent, this);
};
SomeModule.onSomeEvent = function (data)
{
var x = data.x;
var y = data.y;
// ........
Mediator.dispatch ('ThirdEvent', {name: 'Liza', gender: 1});
// now all modules registered for 'ThirdEvent' will get their callbacks executed
};
Typical Mediator operates as a dictionary routing calls from event name to according callback array to execute callbacks from. Now the problem lies in optimization: Mediator.dispatch (...) introduces dynamic objects and therefore polymorphic code which will remain slow and unoptimized when executed in V8. Some events will be fired 60 times per second and will have multiple callbacks, so it will surely benefit from optimizations.
What is the most elegant way to make this code monomorphic without introducing large boilerplate code for every new event?
EDIT: replaced .bind(this) with supplying this as context param as suggested in the comments.
//@event ThirdEvent(name, gender)
. These annotations would then be read by a code preprocessor which would generate constructors code for those automatically. Then in your code you could useMediator.dispatch(new ThirdEvent('Liza', 'gender'));
. Something else you should definitely be looking at is to de-bounce your event dispatching or callback processing when you can. – plalx