Passing a parameter into called function using Dojo lang.hitch

Viewed 947

I am using dojo in ESRI's Web AppBuilder environment (which uses the ESRI Javascript 3.x API).

Anyway, I create a button, and in the button's onClick method, I want to be able to call another function using lang.hitch (to keep function in scope). But the called function takes a parameter, and I can't seem to pass it in. I can only call the function, like this.

this.myDialogBtn1 = new Button({ label: "Create New Location", disabled: false, onClick: lang.hitch(this, this._createNewLocation) }).placeAt(this.createNewLoc)

And of course, my _createNewLocation function needs to take a parameter, like this.

_createNewLocation(param){...do stuff}

I'm not sure how I could pass in that parameter to the onClick method. Just adding the parameter like this doesn't work. It throws a TypeError. Any ideas?

lang.hitch(this, this._createNewLocation(param))

2 Answers

just bind the param

onClick: lang.hitch(this, this._createNewLocation.bind(this,param));

this will pass in the param to the function as the first param, the this is the context your binding the function too

As pointed out in the comment below hitch is dojos implementation of bind and should also then take params, but if thats the case you would not even need to use hitch and could just call

onClick: this._createNewLocation.bind(this,param);

You don't need to use bind if you use lang.hitch. Just pass the param as the third argument. Any arguments provided after the first two will be passed to the function.

onClick: lang.hitch(this, this._createNewLocation, param);

You could use the vanilla bind() method instead if you prefer:

onClick: _createNewLocation.bind(this, param);

myObject.prototype._createNewLocation = function(param, evt) {
    console.log(param, evt);
}
Related