Callback Binding
A small sample to confirm .bind() works like I think and can handle a specific usecase for callbacks
by Jason Butz
HTML
<button id="runBtn">
Run
</button>
JavaScript
class Runner {
constructor() {
this.calls = [];
}
add(cb) {
this.calls.push(cb);
}
run() {
this.calls.forEach((cb) => {
cb.call(null, Date.now());
});
}
}
class App {
constructor() {
this.myValue = 'MY secret value';
var runner = new Runner();
document.getElementById('runBtn').addEventListener('click', () => {
runner.run();
});
this.myCallback = this.myCallback.bind(this);
runner.add(this.myCallback);
}
myCallback(now) {
let text = `${now} - ${JSON.stringify(this.myValue || null)}`;
let el = document.createElement('pre');
el.innerText = text;
document.body.appendChild(el);
}
}
var app = new App();