Search code examples
javascriptdojoscoperequireexecution

Dojo 1.6 hitch() scope of "this" within require statement


I got a weird problem with my dojo app. It's simply about the scope and hitching the object itself. The following code

function(data) {
        console.info(this); // [I]
        var fun = require(["dojo/Deferred"], function(Deferred) {
            console.info(this); // [II]
        });

        lang.hitch(this, fun());
    }

creates this output

Object{...} // from [I]
Window index.php [II]

the desired output has to be 2 times the Object. I thought I understood the hitch-mechanism, but by invoking lang.hitch(this, fun()); it seems to me, that "this" is the object which is printed by [I].

I hope you guys can help!

Thanks in advance!


Solution

  • What you want to do is hitch the scope of the callback function:

    function(data) {
            console.info(this); // [I]
            var fun = require(["dojo/Deferred"], lang.hitch(this,function(Deferred) {
                console.info(this); // [II]
            }));
    }
    

    rather than hitching to the return result of the require function after being evaluation lang.hitch(this, fun());