Is there anything inherently dangerous about instantiating a dojo class like this?
I need to be able to instantiate an object of a class in Dojo at runtime and mix it into another object (kind of like specifying an extends
开发者_运维知识库or an implements
in Java, but at runtime). and I came up with the following solution:
var declaredClassBackup = this.declaredClass; // backup the "declaredClass"
var mixinObject = null;
try {
dojo.require(kwArgs.mixinClassName);
/*
* Eval the mixinClassName variable to get the Function reference,
* then call it as a constructor with our mixinSettings
*/
mixinObject = new (eval(kwArgs.mixinClassName))(kwArgs.mixinSettings);
} catch (e){
if(console){
console.error("%s could not be loaded as a mixin.",
kwArgs.mixinClassName);
}
mixinObject = new package.path.DefaultMixin(kwArgs.mixinSettings);
}
dojo.mixin(this, mixinObject);
/*
* Re-set the declaredClass name back to that of this class.
*/
this.declaredClass = declaredClassBackup;
What could go wrong with this type of code, if anything? (How would you make it more robust?) Also, is there something I could've just missed in dojo that would've done this for me more gracefully?
At least two things can go wrong:
- Your code assumes that a dynamically loaded module is loaded synchronously with
dojo.require()
. It is true only for the default loader. The XD loader will load things asynchronously breaking your logic. - An object is instantiated and its properties copied using
dojo.mixin()
, which by necessity will flatten it. It means:- It may override some internals (you preserve
declaredClass
, but there may be others). - OOP helpers (like
this.inherited()
) will be broken for copied methods.
- It may override some internals (you preserve
But if these restrictions fit your use case, you should be fine.
It is hard to suggest improvements because it is not clear what you are trying to achieve. If you want to add flat mixins to an object, the only thing you need to make sure that the objects are truly flat.
Minor improvements to your code:
declaredClass
is defined on object's prototype, not on object itself ⇒ you don't need to preserve it. Just delete it from the object itself://var declaredClassBackup = this.declaredClass; // backup the "declaredClass" // no need // the rest of your code ... /* * Re-set the declaredClass name back to that of this class. */ //this.declaredClass = declaredClassBackup; // no need delete this.declaredClass;
Instead of
dojo.mixin()
you can usedojo.safeMixin()
, which skipsconstructor
and decorate methods. This method is available since Dojo 1.4 (including the current trunk).
精彩评论