开发者

Javascript Closure/Event Handling Nightmare

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 acc开发者_Python百科urate 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?


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:

myClickableThing.addListener('click', function(event){this._clickFunction(event)});

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.


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 the evt 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:

   SomeClass = Base.extend({
    _clickFunction: function(evt) {
          alert(this.someBaseClassMethod() + 'x: ' + evt.targetX+ 'y:'+ evt.targetY);
    },
    go: function(){
          myClickableThing.addListener('click', this._clickFunction.bind(this));
    }
   }

Fixed Version:

  SomeClass = Base.extend({
    _clickFunction:null,
    constructor: function(){
      this._clickFunction = function(evt) {
          alert(this.someBaseClassMethod() + 'x: ' + evt.targetX+ 'y:'+ evt.targetY);
      }
    },
    go: function(){
          myClickableThing.addListener('click', this._clickFunction);
    }
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜