[英]How do I create an event listener (mouse click) that will reference a method from within a class?
Class Example:类示例:
$(document).ready(function(){
var $ = document.getElementById.bind(document);
class Farkle
{
constructor()
{
this.playerCount = 0;
this.failBit = 0;
this.playerName = [];
this.diceRoll = [];
this.frontEndDice = [
"img/Alea_1.png", "img/Alea_2.png", "img/Alea_3.png",
"img/Alea_4.png", "img/Alea_5.png", "img/Alea_6.png"
]
this.diceID = ["d0", "d1", "d2", "d3", "d4", "d5"]
$('rollButton').onclick = this.testMethod; // will this work?
}
testMethod()
{
console.log('I have access!');
}
}
});
I am still learning how to make connections between my HTML and my JavaScript, so I am trying to find ways of building good habits early on.我仍在学习如何在我的 HTML 和我的 JavaScript 之间建立联系,所以我试图找到尽早建立良好习惯的方法。 I would like to understand the proper way of connecting a mouse-click event to calling (referencing?) a method from within a class.
我想了解将鼠标单击事件连接到从类中调用(引用?)方法的正确方法。
I've tried relocating my .onclick
event in a few spots throughout my code, from the global scope, to within methods, and now I have it sitting in my constructor for the class.我已经尝试将我的
.onclick
事件重新定位在我的代码中的几个位置,从全局范围到方法内,现在我将它放在我的类的构造函数中。 Having it here works.把它放在这里有效。 I haven't explored the limitations of this, but is this an inappropriate way of creating an event listener that will reference a method within a class?
我还没有探讨过它的局限性,但这是创建将引用类中的方法的事件侦听器的不当方法吗?
Nesting the EventListener within the EventListener which instantiates the object has allowed me to reference the method.在实例化对象的 EventListener 中嵌套 EventListener 允许我引用该方法。
$('startButton').addEventListener('click', function(event) {
var fark = new Farkle();
console.log('fark is an instance of Farkle?', fark instanceof Farkle);
fark.setup();
$('rollButton').addEventListener("click",fark.testFunction);
});
Thank you to @ ADyson who has made this a little bit more clear.感谢@ADyson ,他使这一点更加清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.