如何在使用类方法作为回调的类中添加事件处理程序?

2022-01-15 00:00:00 oop event-handling javascript

如何在一个类中添加一个事件处理程序,并将类方法作为回调?

How do I add an event handler inside a class with a class-method as the callback?

<div id="test">move over here</div>
<script>
    oClass = new CClass();
    function CClass()
    {
        this.m_s = "hello :-/";
        this.OnEvent = OnEvent;
        with(this)
        {
            var r = document.getElementById("test");
            r.addEventListener('mouseover', this.OnEvent);  // this does NOT work :-/
        }
      
        function OnEvent()
        {
            alert(this);    // this will be the HTML div-element
            alert(this.m_s);    // will be undefined :-()
        }
    }
</script>

是的,我知道一些让它工作的怪癖,但是当这些事件处理程序被引入时,预期的方式是什么???我再次有一种苦涩的感觉,没有人真正生活在 OOP 中:-(

Yes I know some quirks to make it work but what would be the intended way when these event handlers were introduced ??? I again have the bitter feeling, that no-one truly lives OOP :-(

这里给你玩:https://jsfiddle.net/sepfsvyo/1/

推荐答案

事件监听回调中的 this 将是触发事件的元素.如果您希望 this 成为您的类的实例,那么:

The this inside the event listener callback will be the element that fired the event. If you want the this to be the instance of your class, then either:

将函数绑定到类实例:

使用 Function.prototype.bind,将创建​​一个新函数,它的 this 值将始终是您指定的值(类实例):

Using Function.prototype.bind, will create a new function that its this value will always be what you specify it to be (the class instance):

r.addEventListener('mouseover', this.OnEvent.bind(this));
//                                          ^^^^^^^^^^^

将函数包装在匿名函数中:

var that = this;
r.addEventListener('mouseover', function(ev) { that.OnEvent(ev); });
//                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

或使用箭头函数(所以不需要 that):

or use an arrow function (so no need for that):

r.addEventListener('mouseover', ev => this.OnEvent(ev));
//                              ^^^^^^^^^^^^^^^^^^^^^^

注意:正如下面的评论中提到的,上述两种方法都将不同的函数传递给 addEventListener(带有 bind 的函数创建一个新函数,而异常函数显然是 !== this.OnEvent).如果您稍后要删除事件侦听器,则必须存储对该函数的引用:

Note: As mentioned in a comment bellow, both of the above methods pass a different function to addEventListener (the one with bind create a new function, and the anounimous function is obviously !== this.OnEvent). If you are going to remove the event listener later, you'll have to store a reference to the function:

var reference;
r.addEventListener('mouseover', reference = this.OnEvent.bind(this));
//                              ^^^^^^^^^^^^

或:

var reference;
var that = this;
r.addEventListener('mouseover', reference = function(ev) { that.OnEvent(ev); });
//                              ^^^^^^^^^^^^

然后你可以像这样删除事件监听器:

then you can remove the event listener like:

r.removeEventListener('mouseover', reference);

相关文章