简体   繁体   中英

ECMAscript6 class scopes in events

How to bind a class method in to click-event?

In this sample, the context is 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

In your constructor you need to bind clickEvents to 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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