如何將類方法綁定到click事件中?事件中的ECMAscript6類作用域
在此示例中,上下文是按鈕。我也嘗試了箭頭符號,沒有任何成功。
"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>
此致 ^ h
你是怎麼使用箭頭的? – Bergi