[英]How do I create an event listener on a property in every instance of a class?
[英]How do I create an event listener (mouse click) that will reference a method from within a class?
類示例:
$(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!');
}
}
});
我仍在學習如何在我的 HTML 和我的 JavaScript 之間建立聯系,所以我試圖找到盡早建立良好習慣的方法。 我想了解將鼠標單擊事件連接到從類中調用(引用?)方法的正確方法。
我已經嘗試將我的.onclick
事件重新定位在我的代碼中的幾個位置,從全局范圍到方法內,現在我將它放在我的類的構造函數中。 把它放在這里有效。 我還沒有探討過它的局限性,但這是創建將引用類中的方法的事件偵聽器的不當方法嗎?
在實例化對象的 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);
});
感謝@ADyson ,他使這一點更加清晰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.