I got problems to handle async calls.
For example I want to load some modules dynamically with requirejs.
Currently I use the subscriber-publisher pattern. Unfortunately this makes my code
in some situation really confusing…:
imagine there is a working event system in the object
var loader = {
load: function(modules) {
// do a async requirejs call
require(modules, function(){
// map arguments to normal array
var modules = [].slice().call(arguments);
// fire loaded event, pass modules
this.trigger('loaded', modules);
}.bind(this));
}
};
var parent = {
// do some initialization work
initialize: function() {
// execute the second initialization when our modules have finished loading async
loader.on('loaded', this.secondInitialize, this);
// require the given modules in the array
loader.load(['one', 'two', 'three']);
},
secondInitialize: function(modules) {
var three = new modules[2]();
// do something with the 'three' module
}
};
As you see this is really confusing.
Are there any other design patterns which allow handsome handling of async calls?
Look into the jQuery Deferred object. (Even without jq, most libraries have an implementation of javascript promises)
With it you can do something like this:
Not exactly your scenario but you get the idea. It becomes relatively easy to compose asynchronous atoms.