Search code examples
javascriptscopedojowidgetdom-events

dojo - lang.hitch for widget function


I have a custom widget and I am curious if I can use lang.hitch in a particular way. Here is the scenario:

Say I have a custom widget that contains a Button. That Button needs a function attached to its onClick event. So, in my template I have:

<button data-dojo-type="dijit/form/Button" data-dojo-attach-event="onClick : _onButtonClick" />

Then, in my widget .js file I have:

_onButtonClick : function(evt) {
    //do something here that needs the scope of my widget (this)
}

I know I could remove the data-dojo-attach-event from my template and use dojo.connect with lang.hitch in postCreate, but I'm wondering if I could just simply convert the _onButtonClick function to this:

_onButtonClick : lang.hitch(this, function(evt) {
    //do something here that needs the scope of my widget (this)
})

Solution

  • data-dojo-attach-event automatically makes the scope of this be the parent widget.

    I'm not 100% sure, but I don't think the context of this in the snippet declare([/deps/,{

        _onButtonClick : lang.hitch(this, function(evt) {
          //do something here that needs the scope of my widget (this)
        })
    
    });
    

    is what you want to. I believe when that function is bound it will be the scope that the declare function is executed in, rather than the instance of the widget.