Javascript 闭包/事件处理噩梦
我正在使用 ovi 地图 API,并且有一条带有事件处理程序的折线。事件处理程序如下所示
SomeClass = Base.extend({
_clickFunction: function(evt) {
alert(this.someBaseClassMethod() + 'x: ' + evt.targetX+ 'y:'+ evt.targetY);
},
go: function(){
myClickableThing.addListener('click', this._clickFunction.bind(this));
}
}
第一次单击我的东西时,我得到的 X 和 Y 与光标的像素位置和准确的时间戳是正确的。对于同一条折线的每次后续点击,我都会得到完全相同的 X、Y 和时间戳。有人有任何想法或解决方法吗?
I am using the ovi maps API and I have a polyline with an event handler. The event handler looks like the following
SomeClass = Base.extend({
_clickFunction: function(evt) {
alert(this.someBaseClassMethod() + 'x: ' + evt.targetX+ 'y:'+ evt.targetY);
},
go: function(){
myClickableThing.addListener('click', this._clickFunction.bind(this));
}
}
The first time I click my thing I get X and Y that are correct for the pixel position of the cursor and an accurate timestamp. For every subsequent click on the same polyLine I get the exact same X,Y,and Timestamp. Does anyone have any thoughts or a workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论如何,我不确定 OVImap API,但我猜测它会将自己的事件对象传递给您的处理程序方法。看看这是否给你正确的价值观。
您的侦听器功能将类似于:
希望这有帮助。
顺便说一句,我们在谷歌地图和一个特定的浏览器上遇到了类似的问题,其中 evt 变量的范围不正确或类似的问题。
我不确定这是否是你的问题。
Anyways I am not sure of the OVImap API but I am guessing it will pass its own event object to you to the handler method. see if that gives you the right values.
your listener function will be something like:
Hope this helps.
On a side note wEll we ran into a similar issue on google maps and one particular browser where in the evt variable was not scoped correctly or something of that sort.
I am not sure if that is your problem.
首先,感谢所有回答的人。我确实设法解决了这个问题,尽管我不能告诉你为什么它一开始就不起作用(如果有人经常在 ECMAscript 标准中摸索,请随时与我联系)。问题肯定是
this._clickFunction.bind(this))
。无论出于何种原因,这都会创建一个保留evt
对象的闭包。解决方案(正如你们中的一些人在评论中建议的那样)只是通过在构造函数中设置函数来解决该问题。原始版本:
固定版本:
First off, thanks for all those that answered. I did manage to solve this problem although I can't tell you why it didn't work in the first place(If anyone regularly fishes around in the ECMAscript standard please feel free to contact me). The issue was definitely
this._clickFunction.bind(this))
. For what ever reason this creates a closure that retains theevt
object. The solution(as some of you suggested in the comments) was simply to work around that line by setting the function up in the constructor.Original:
Fixed Version: