Homam's Mind

Monday, December 7, 2009

Hollywood Principle

Today I was working on refactoring some names in Hyzobox In/Out API. It is my personal favorite piece of code in the whole platform. In summary it allows the publisher of the game to customize the game in runtime dynamically by injecting codes and executing some functions in the context of the game (In) and to get notified about the events that are occurring inside the game (Out).

Inversion of Control is very natural in JavaScript and it has been used extensively in In/Out API. It's quite different from popular prototype pattern but most everyday JavaScript programmers use IoC even though they don't usually notice it.

Here is a sample in our API:

We register an event listener in Hyzobox, waiting for landing view of the game to be loaded:


var hb = Hyzobox.createInstance();
var landingview_loaded = function(hbEvent) {
// do something with hbEvent
}
hb.addEventListener('landingview_loaded', landingview_loaded);


It's is clear that we don't have control over when landingview_loaded event will be fired and its handler will be called.

hbEvent argument that is of type Hyzobox.Event has a data attribute that is of type Object. In this example the data is a LandingView instance. We can interact with this object in the event handler:


var landingview_loaded = function(hbEvent) {
var view = hbEvent.data;
view.inject('a-container-id', 'some text');
};


In this example we are injecting 'some text' to an element identified by 'a-container-id' inside landing view.

addEventListener() is part of Out and inject() is part of In API. If we want to listen to the events that are occurring inside a particular view, we should register their halnders after the view has been loaded:


var landingview_loaded = function(hbEvent) {
var view = hbEvent.data;
view.attachEventListener('playNow', function playNowHandler(playNowHbEvent) {
// do something with playNowHbEvent
});
};


And so on, we can have many nested Ins and Outs.

It's easy to see that in these examples the control has been transferred to the event handlers. The caller raise the events but it's the responsibility of the handlers to control the functionalities.

I don't want to go into the the details now, because the work hasn't yet been finished on these APIs. Once released, we will post them in Hyzobox documentations and Hyzonia tech blog in the following weeks.

No comments: