Reputation: 750
I working with a pre-built client application all written with Dojo 1.8 (AMD style) which I need to extend.
I have access to the source code but want to leave it unchanged where possible and instead favor overrides (that's how the application plug-in framework works, anything else would be a hack).
My script loads only after the base application script. I cannot modify djConfig for example, nor anything else that would occur before the base application modules are loaded.
Here is my question: I would like to extend one of the base application classes (created with declare) and apply my overrides globally -- even on pre-loaded modules which already required the module containing this class (but not yet instantiated it).
So far, the best solution that I found is to use require() to alias the module containing the class. But this only works with modules that require the class after I could register the alias.
Upvotes: 2
Views: 1491
Reputation: 7352
The Dojo AMD Loader documentation states:
Once a module value has been entered into the module namespace, it is not recomputed each time it is demanded. On a practical level, this means that factory is only invoked once, and the returned value is cached and shared among all code that uses a given module. (Note: the dojo loader includes the nonstandard function require.undef, which undefines a module value.)
This means that if you modify the prototype of the module, the change will propagate throughout the application, even to the instances created before the change, because this is how JavaScript works.
To modify a prototype of class created via dojo/_base/declare
, there is an extend()
method defined on the constructor:
require(['App'], function(App) {
App.extend({
run: function() {
// override `run` method here
}
});
});
See it in action: http://jsfiddle.net/phusick/HxkFs/
Upvotes: 4