2

我在 ESRI 的 Web AppBuilder 环境(使用 ESRI Javascript 3.x API)中使用 dojo。

无论如何,我创建了一个按钮,并且在按钮的 onClick 方法中,我希望能够使用 lang.hitch 调用另一个函数(以将函数保持在范围内)。但是被调用的函数带了一个参数,我好像传不进去,只能调用函数,像这样。

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

当然,我的 _createNewLocation 函数需要带一个参数,就像这样。

_createNewLocation(param){...do stuff}

我不确定如何将该参数传递给 onClick 方法。像这样添加参数是行不通的。它抛出一个类型错误。有任何想法吗?

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

4

2 回答 2

2

只需绑定参数

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

this 会将参数作为第一个参数传递给函数,这this也是您绑定函数的上下文

正如下面评论中所指出的,hitch 是 dojos 的 bind 实现,然后也应该使用参数,但如果是这样的话,你甚至不需要使用 hitch 并且可以调用

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

于 2019-10-08T23:56:32.770 回答
1

如果您bind使用lang.hitch. 只需将参数作为第三个参数传递。在前两个之后提供的任何参数都将传递给函数。

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

如果您愿意,可以改用 vanillabind()方法:

onClick: _createNewLocation.bind(this, param);

myObject.prototype._createNewLocation = function(param, evt) {
    console.log(param, evt);
}
于 2019-10-18T12:26:03.580 回答