ECMAscript6类在事件中的作用域
ECMAscript6 class scopes in events
如何将类方法绑定到click-event?
在这个示例中,上下文是button。我也尝试过箭头符号,但没有成功。
"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
在构造函数中,您需要将clickEvents绑定到this
$('#btn').bind('click', this.clickEvents.bind(this));
因为它看起来像你想要删除你的even监听器之后你应该实际存储一个引用到那个绑定函数因为那是你需要在你的doUnBindings方法中使用的。
最终你可能想要这样的东西
"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');
}
}
您可以轻松地在这里使用箭头符号,只需在构造函数中创建特定于实例的方法:
class Foo {
constructor() {
this.clickEvents = (e) => {
e.stopPropagation();
this.sayBoo();
};
}
doBindings() {
$('#btn').bind('click', this.clickEvents);
}
doUnbindings(){
$('#btn').unbind('click', this.clickEvents);
}
sayBoo() { … }
}
或者,您可以使用@Jonathan充实的bind
,或任何标准方法。
相关文章:
- 将作用域绑定到事件处理程序,但保留原始参数
- 直接在DOM事件处理程序中调用作用域函数的最短方法是什么
- 作用域和将参数传递给动态创建的事件处理程序时出现问题
- jQuery 解绑在作用域中声明的事件
- 如何从事件处理程序调用 AngularJS 作用域定义的函数
- 订阅子作用域上的事件,并在broadcastemit中返回回调
- Angular.js-视图不't在resize事件中更改作用域变量时更新
- javascript:如何更改"这个“;事件的作用域
- AngularJS事件,在应用所有作用域后触发
- JavaScript事件处理程序作用域
- 变量作用域和事件处理程序
- HTML5 drop事件具有不同的e.target作用域
- Javascript作用域问题:函数在$(doc).ready()中可用,但在事件处理程序中不可用
- Javascript事件处理程序在其作用域之外使用变量的问题
- JQuery事件之外的变量作用域
- 如何知道函数作用域上的JavaScript事件源
- Javascript作用域和点击事件
- JavaScript事件回调函数的作用域问题
- 事件处理程序函数超出了for的作用域
- ECMAscript6类在事件中的作用域