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

How adding event handler inside a class with a class-method as the callback?(如何在使用类方法作为回调的类中添加事件处理程序?)
本文介绍了如何在使用类方法作为回调的类中添加事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

这篇关于如何在使用类方法作为回调的类中添加事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)