In typewriting, itβs hard to understand what a function call is, especially when you βbindβ it. Such as:
HTML
<a id="One"></a> <a id="Two"></a>
and some code that creates two objects
let x = new MyClass("I am one", "One"); let y = new MyClass("and I am two", "Two");
with MyClass
class MyClass { private _myInstance: string; constructor(ID: string, domID: string) { this._myInstance = ID; document.getElementById(domID).addEventListener('click', this.print.bind(this)); } public print() { console.log(this._myInstance); } }
You will correct "I am one" when you click on the "One" element and "And I am two" when you click on the second element.
The situation is more complicated with the removal. You need to add the object variable with the binding enabled so that the my class changes to:
class MyClass { private _myInstance: string; private _myDomID: string; private _myFunc = this.print.bind(this); constructor(ID: string, domID: string) { this._myInstance = ID; this._myDomID = domID; document.getElementById(domID).addEventListener('click', this._myFunc); } public print() { console.log(this._myInstance); } public cleanUp() { document.getElementById(this._myDomID).removeEventListener('click', this._myFunc); }
}
source share