I have not been able to find an answer to this question, however it is possible I just don't know what to search for.
This is for a "Cookie Clicker" type game. I have a list of servants, which, when unlocked, add an entry to a <ul>
, with buttons to hire more of them, and appropriate info.
However, I have not been able to bind the buttons to the instance's methods. How would I achieve that, or something similar if my implementation is suboptimal ?
<ul id="servants"></ul>
<template id="servant-template">
<li>
<span class="count-span"></span> <span class="name-span"></span> :
+<span class="value-span"></span>/s
<button type="button" class="hire-button">
Hire (<span class="hire-cost"></span>$)
</button>
</li>
</template>
class Servant {
constructor(name, value) {
this.count = 0;
this.name = name;
this.value = value;
this.cost = value;
this.unlocked = false;
}
work() {
if (!this.unlocked) return;
add_score(this.count * this.value * this.level);
}
hire() {
if (!this.unlocked || balance < this.cost) return;
balance -= this.cost;
this.count += 1;
this.cost *= 2 ** this.value;
this.update_gui();
}
unlock() {
this.unlocked = true;
const template = document.querySelector("#servant-template");
const clone = template.content.firstElementChild.cloneNode(true);
clone.id = `servant-${this.name}`;
console.log(clone);
clone.querySelector(".hire-button").onclick = function () {
this.hire(); //Doesn't work because "this" actually is the button at call time
};
servants_gui.appendChild(clone);
this.update_gui();
}
update_gui() {
if (!this.unlocked) return;
const gui = document.querySelector(`#servant-${this.name}`);
console.log(gui);
gui.querySelector(".count-span").innerHTML = this.count;
gui.querySelector(".name-span").innerHTML = this.name;
gui.querySelector(".value-span").innerHTML = this.value;
gui.querySelector(".hire-cost").innerHTML = this.cost;
}
}
const servants = [new Servant("Miners", 1)];
servants[0].unlock();