Javascript 从html元素调用函数时引用函数的类
我有一个类,在加载html元素时为其分配eventListener。单击该html元素时,它会调用同一类中的函数,如下所示:Javascript 从html元素调用函数时引用函数的类,javascript,Javascript,我有一个类,在加载html元素时为其分配eventListener。单击该html元素时,它会调用同一类中的函数,如下所示: class LiveViewController extends ViewController{ viewLoads(){ $("#mydiv")[0].addEventListener("click",this.someFunction); } someFunction(){ console.log(this); } } 问题是,我希望以某种方式
class LiveViewController extends ViewController{
viewLoads(){
$("#mydiv")[0].addEventListener("click",this.someFunction);
}
someFunction(){
console.log(this);
}
}
问题是,我希望以某种方式在someFunction中引用类的实例,但这引用了元素本身。您建议的方法是什么?当您在jQuery中指定一个用作事件处理程序的函数时,该函数可以访问启动事件的原始DOM元素,如下所示。因此,经典的解决方案是将处理程序中的类上下文作为self关闭: 您甚至不需要传递上下文:
class LiveViewController extends ViewController{
viewLoads(){
var self = this;
$("#mydiv")[0].addEventListener("click", function() {
self.someFunction();
});
}
someFunction(){
console.log(this);
}
}
最后,您可以使用.bind绑定适当的上下文:
class LiveViewController{
viewLoads(){
$("#mydiv")[0].addEventListener("click", this.someFunction.bind(this));
}
someFunction(){
console.log(this);
}
}
要获得对实例化对象和dom元素的访问权,可以使用
class LiveViewController extends ViewController{
viewLoads(){
var self = this;
$("#mydiv")[0].addEventListener("click", function() {
self.someFunction(this);
});
}
someFunction(element){
console.log(this);
console.log(element);
}
}
您可以尝试以下方法:
class LiveViewController extends ViewController {
viewLoads(){
// You can pass data to the callback directly as event.data in jQuery
$("#mydiv").on('click', {self: this}, this.someFunction);
// or Another way would be to use bind
// $("#mydiv").click(this.someFunction.bind($, this));
// someFunction(self, event) - definition
}
someFunction(event){
console.log(event.data.self);
}
}
“为什么我不能+5这个答案可能会重复?@GeorgeAvgoustis你也可以接受这个答案。我会的,只是等待时间限制。”。不是为了延长时间,而是。。如果我想同时访问类和元素,我该怎么做?好的,这是一个好方法。这样做是否太愚蠢:$rollDieDiv[0]。addEventListenerclick,this.rollDiePressed.bind{element:$rollDieDiv[0],classInstance:this}?
class LiveViewController extends ViewController {
viewLoads(){
// You can pass data to the callback directly as event.data in jQuery
$("#mydiv").on('click', {self: this}, this.someFunction);
// or Another way would be to use bind
// $("#mydiv").click(this.someFunction.bind($, this));
// someFunction(self, event) - definition
}
someFunction(event){
console.log(event.data.self);
}
}