dojo‎ > ‎

addOnLoad gotcha

I wouldn't waste time writing about dojo if I didn't like it.  But I can get frustrated as I wrangle with understanding how it works.
consider the addOnLoad function with the following "gotcha" example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
    "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js"></script>
        <script type="text/javascript">
            myObject = function(variable){
                this.variable = variable?variable:"default value";
                this.funcA = function(){
                    alert("Variable is: " + this.variable);
                }
                this.funcB = function(){
                    this.funcA?this.funcA():alert(this);
                }
            }
            myInstance = new myObject;
            dojo.addOnLoad(myInstance.funcB);
        </script>
    </head>
    <body></body>
</html>
Seems straight forward enough, right?
wrong!

The alert contains a string of this.funcB, and has no context to reference funcA.  To get the above to function as expected, you need to change the addOnLoad call to:
dojo.addOnLoad(myInstance, "funcB");
Now dojo passes the object, not just the function of the object, and it now calls over to myInstance.funcA and alerts the object's variable!
Comments