Views: 3644
Number of votes: 0
Average rating:

Dojo - How to keep the widget's scope

When binding an event in JavaScript the scope outside the binding is not the same as inside. Which means that "this" is not the same outside as inside the binding.

Below there is a JavaScript example, which console.logs two different "this". The first console.log prints the object Foo, the second console.log prints the button object.




However, sometimes we want to keep the scope. This is often solved by putting "this" in a variable, like the example below. This way both console.logs prints the Foo object.




In Dojo there is a built-in function, hitch, which can keep the scope. This can come in handy when developing Dijit widgets.

In the example below hitch forces the on method to retain the original scope. In this way we keep "this" inside the callback, and we do not need to create a variable for "this" like we did above.



Jan 08, 2016

Please login to comment.