简体   繁体   English

JavaScript事件处理程序功能范围控制

[英]JavaScript event handler function scope controll

I've got 3 interconnected methods inside an object: 我在一个对象中有3个互连的方法:

    dragStartHandler: function(e) {
        console.log(e.type, 'dragstart', e.pageX, e.pageY);
        document.addEventListener('mousemove', this.dragMoveHandler, false);
        document.addEventListener('mouseup', this.dragEndHandler.bind(this), false);
    },

    dragMoveHandler: function(e) {
        console.log(e.type, 'dragmove', e.pageX, e.pageY);
        this.updateRotation();
    },

    dragEndHandler: function(e) {
        console.log(e.type, 'dragend', e.pageX, e.pageY);
        document.removeEventListener('mousemove', this.dragMoveHandler, false);
    },

They handle rotation based on mouse pointer position. 它们根据鼠标指针的位置处理旋转。 I can't figure out what to do to have access to original this inside dragMoveHandler and be able to remove the element listener at the same time. 我不知道该怎么做能够获得原来里面dragMoveHandler并能够在同一时间删除元素监听。 I tried using .bind(this) but it returns anonymous function which I can't remove inside dragEndHandler . 我尝试使用.bind(this),但是它返回匿名函数,该函数无法在dragEndHandler内部删除

Is there a technique I'm not aware of? 有我不知道的技术吗?

In the surrounding class you have to remember your class pointer, since this in javascript always points to the current execution/event context. 在周边类,你要记住你的类指针,因为this在javascript总是指向当前执行/事件上下文。

First of all I would suggest to rewrite your class definition to not use object-literal-syntax if possible. 首先,我建议您重写类定义,以尽可能使用object-literal-syntax。

Because then you could take advantage of a common pattern where you "remember" the original this reference in a variable (named self in this example): 因为那样的话,你可以采取一个共同的模式,你“记住”原来的优势, this在一个变量(命名引用self在这个例子中):

var MyClass = function(){
  var self = this; // this line is important, since `this` can change you have to save it
  var dragStartHandler = function(e) {
        console.log(e.type, 'dragstart', e.pageX, e.pageY);
        document.addEventListener('mousemove', self.dragMoveHandler, false);
        document.addEventListener('mouseup', self.dragEndHandler.bind(self), false);
    }
  var dragMoveHandler = function(e) {
        console.log(e.type, 'dragmove', e.pageX, e.pageY);
        self.updateRotation();
    }

  var dragEndHandler = function(e) {
        console.log(e.type, 'dragend', e.pageX, e.pageY);
        document.removeEventListener('mousemove', self.dragMoveHandler, false);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM