如何访问点击处理函数中的函数?
How to access function in click handler function?
我创建这个 class 使用纯 javascript:
var SelectFeature = /*@__PURE__*/(function (Select) {
function SelectFeature() {
Select.call(this, {
condition: ol.events.condition.click
});
}
this.on('select', function (e) {
//some logic
});
if (Select) SelectFeature.__proto__ = Select;
SelectFeature.prototype = Object.create(Select && Select.prototype);
SelectFeature.prototype.constructor = Select;
return SelectFeature;
}(ol.interaction.Select));
如您所见,我将 ol.interaction.Select 作为参数传递给 class 并使用 Select.call() SelectFeature 中的方法作为构造函数。
这是 ol.interaction.Select class 的 description。
ol.interaction.The select class 有一个名为 getFeatures() 的成员。
我尝试在单击某些 DOM 元素时访问此方法(此块位于 SelectFeature class 内):
$("#popupFeat-closer").click(function () {
this.getFeatures();
});
单击 DOM 元素时会触发上面的代码,但是在这一行:
this.getFeatures();
我收到这个错误:
Uncaught TypeError: this.getFeatures is not a function
我的问题是如何访问位于点击事件处理程序中的 getFeatures 函数?
就像评论中提到的那样,您遇到了上下文问题。几乎每个库或框架都有一种方法来保持上下文,在 jQuery 中,您可以使用 proxy
方法来实现。这样的东西应该可以工作,
$("#popupFeat-closer").click($.proxy(function () {
this.getFeatures();
}), this);
我会说使用 library/framework 方法解决这些问题总是好的,但是 "old" 方法也可以,
var self = this;
$("#popupFeat-closer").click(function () {
self.getFeatures();
});
我创建这个 class 使用纯 javascript:
var SelectFeature = /*@__PURE__*/(function (Select) {
function SelectFeature() {
Select.call(this, {
condition: ol.events.condition.click
});
}
this.on('select', function (e) {
//some logic
});
if (Select) SelectFeature.__proto__ = Select;
SelectFeature.prototype = Object.create(Select && Select.prototype);
SelectFeature.prototype.constructor = Select;
return SelectFeature;
}(ol.interaction.Select));
如您所见,我将 ol.interaction.Select 作为参数传递给 class 并使用 Select.call() SelectFeature 中的方法作为构造函数。
这是 ol.interaction.Select class 的 description。
ol.interaction.The select class 有一个名为 getFeatures() 的成员。 我尝试在单击某些 DOM 元素时访问此方法(此块位于 SelectFeature class 内):
$("#popupFeat-closer").click(function () {
this.getFeatures();
});
单击 DOM 元素时会触发上面的代码,但是在这一行:
this.getFeatures();
我收到这个错误:
Uncaught TypeError: this.getFeatures is not a function
我的问题是如何访问位于点击事件处理程序中的 getFeatures 函数?
就像评论中提到的那样,您遇到了上下文问题。几乎每个库或框架都有一种方法来保持上下文,在 jQuery 中,您可以使用 proxy
方法来实现。这样的东西应该可以工作,
$("#popupFeat-closer").click($.proxy(function () {
this.getFeatures();
}), this);
我会说使用 library/framework 方法解决这些问题总是好的,但是 "old" 方法也可以,
var self = this;
$("#popupFeat-closer").click(function () {
self.getFeatures();
});