简体   繁体   English

事件中的ECMAscript6类范围

[英]ECMAscript6 class scopes in events

How to bind a class method in to click-event? 如何将类方法绑定到点击事件?

In this sample, the context is button. 在此示例中,上下文是button。 I've also tried the arrow-notation, without any success. 我也尝试了箭头符号,但没有成功。

 "use strict"; class Foo { constructor() { $('html').prepend('<button id="btn">Click me!</button>'); $('#btn').bind('click', this.clickEvents); } clickEvents(e) { //Have to use as a function, otherwise unbind won't work e.stopPropagation(); // How to point to sayBoo-function? debugger; this.sayBoo(); //Points to <button id="btn"... } doUnBindings(){ $('#btn').unbind('click', this.clickEvents); } sayBoo() { alert('boo'); } } const f = new Foo(); // eslint-disable-line no-unused-vars, prefer-const 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.1/es6-shim.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Yours H 你的H

In your constructor you need to bind clickEvents to this 在您的构造函数中,您需要将clickEvents绑定this

$('#btn').bind('click', this.clickEvents.bind(this));

And since it looks like you want to remove your even listener later on you should actually store a reference to that bound function because that's what you'll need to use in your doUnBindings method. 并且由于您似乎想稍后删除偶数侦听器,因此您实际上应该存储对该绑定函数的引用,因为这是您需要在doUnBindings方法中使用的引用。

So ultimately you probably want something that looks like this 所以最终您可能想要这样的东西

"use strict";
class Foo {
    constructor() {
        $('html').prepend('<button id="btn">Click me!</button>');
        this.boundClickEvents = this.clickEvents.bind(this);
        $('#btn').bind('click', this.boundClickEvents);
    }

    clickEvents(e) {
      //Have to use as a function, otherwise unbind won't work
        e.stopPropagation();
        // How to point to sayBoo-function?
        debugger;
        this.sayBoo(); //Points to <button id="btn"...
    }

    doUnBindings(){
      $('#btn').unbind('click', this.boundClickEvents);
    }

    sayBoo() {
        alert('boo');
    }
}

You can easily use the arrow notation here, just create the instance-specific method in the constructor: 您可以在此处轻松使用箭头符号,只需在构造函数中创建特定于实例的方法:

class Foo {
    constructor() {
        this.clickEvents = (e) => {
            e.stopPropagation();
            this.sayBoo();
        };
    }
    doBindings() {
        $('#btn').bind('click', this.clickEvents);
    }
    doUnbindings(){
        $('#btn').unbind('click', this.clickEvents);
    }
    sayBoo() { … }
}

Alternatively you can use bind as fleshed out by @Jonathan, or any of the standard approaches . 或者您可以使用bind由@Jonathan跃然纸上,或任何一种标准方法

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

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