Reputation: 3721
Why is it that when I use the dojo.hitch function and try to reference the "this" operator inside it, that it gives me reference to the wrong object?
console.debug(dijit.byId("widgetName")); //works as expected and prints out the window object
dojo.hitch(dijit.byId("widgetName"), tester())(); //this should be executing the tester function in the scope of the widget object
function tester() {
console.debug(this); //prints out the Javascript Window object instead of the widget object!!!!
}
Thanks
Upvotes: 2
Views: 6120
Reputation: 53206
Based on what you have just shown, I can now safely provide an answer explaining what is wrong.
When you do a dojo.hitch()
you should not call the function inside of it, but instead call the result of the function. That is, you need to provide dojo.hitch
with a reference to the function to hitch, not the result of invoking that function.
In your example, you are calling tester()
(which invokes the function tester
) inside of the dojo.hitch()
, which calls the tester
once. Even though you have dojo.hitch()();
because tester()
does not return a function handler (but the result of tester
, in this case undefined
), the hitch()();
does nothing. That might have been confusing so I will show you with an example.
Don't do this:
dojo.hitch( context, handler() )();
Instead do this:
dojo.hitch( context, handler )();
So to make what you have very readable you would do this:
widget = dijit.byId("widgetName");
tester = function() {
console.log(this);
}
handle = dojo.hitch(widget, tester);
handle();
Your mistake was trying to call the function from within the dojo.hitch()
. This mistake also was not present in your original question.
Upvotes: 6