Search code examples
javascriptevent-handlingdojodom-events

dojo function with multiple contexts


I have a dojo class created with dojo/_base/declare that includes an onClickHandler. This handler is used by a dijit/form/Button to work with data stored within the class. I need the handler to be able to reference both the Button that triggered the event and the instance of the class to which the handler belongs.

For example, below is the first part of the handler function from the class:

drawToolClick : function(evt) {

    this.drawingtoolbar.deactivate(); // Here `this` should represent the instance of my class

    var parent = this.getParent(); // Here `this` should represent the button that was clicked

I know that I obviously can't use this to represent both, but when I use dojo/_base/lang to hitch my class instance to the function, I do not know which button was clicked (I have multiple buttons using the same handler because they represent an enum). If I leave out the hitch this references the button that was clicked, but I don't know how to get the instance of the class that the handler is part of.

Is there a better way to do this?


Solution

  • So, I finally figured this out. I simply added a variable var self; in my module where the class is defined before the declare statement. Then, in my class constructor function I added self = this;.

    Then in my onclick handler I use this to reference the button that was clicked and I use self to reference the class instance.

    This seems to work alright.