JasonWyatt

This blog is full of stuff, and things.

Find my resume.

permalink

Dynamically Instantiate a Dojo Class At Runtime

Need to create an instance of a class in Dojo without knowing what that class is ahead of time? Will you only have the name of the class that you want to instantiate? Check this out:

/**
 * Create a new instance of a Dojo class.
 *
 * @param className
 *    (String) A fully-qualified name for class, such as 
 *    "my.pack.age.Class"
 * @param constructorSettings
 *    (object) An object that will be passed on to the 
 *    class's constructor.
 */
function instantiateDojoClass(className, constructorSettings){
    try {
        dojo.require(className);
        
        /*
         * Eval the class name to get a reference to the 
         * function, then call it as a constructor using the 
         * constructorSettings object as an argument.
         */
        var obj = new (eval(className))(constructorSettings);
    } catch (e){
        /*
         * Handle any errors that might happen.
         */
        if(console){
            console.error("Could not instantiate %s: %s", classsName, e.message);
        } else {
            alert("Could not instantiate "+className+": "+e.message);
        }
        throw e;
    }
}

The real trickery here is in the line:

var obj = new (eval(className))(constructorSettings);

This evaluates the string className to retrieve a reference to the dojo function that was ‘created’ by the call to dojo.require(..), then calls that function as a constructor by using the new keyword. It passes the constructorSettings object on to the constructor, just like you’d do with any normal dojo instantiation.

blog comments powered by Disqus