Reputation: 1131
I probably missunderstood some concept, but after reading 4 topics on stackoverflow, and documentation for "private members in typescript" - I am still confused.
I am writing simple mouse IO (first typescript project). This is full code of malfunctioning mouse class:
class Mouse {
public left: MouseKeyData = new MouseKeyData();
public right: MouseKeyData = new MouseKeyData();
public whell: MouseKeyData = new MouseKeyData();
public x: number = 0;
public y: number = 0;
private crossBrowserButton(e: any):string {
switch (e.button) {
case 0: return 'left';
case 1: return 'whell';
case 2: return 'right';
case 3: return 'back';
case 4: return 'forward';
}
return 'none';
}
private onMouseDown(e: any):void {
let target: MouseKeyData = this.left;
try {console.log(this.crossBrowserButton(e))} catch (a) {console.warn(a)} finally {}
if(target) {
target.press();
}
}
private onMouseUp(e: any):void {
let target: MouseKeyData = this.left;
if(target) {
target.release();
}
}
private onMouseMove(e: any): void {
this.x = e.pageX;
this.y = e.pageY;
}
public constructor() {
let anchor = document.body;
anchor.addEventListener('mousedown', this.onMouseDown);
anchor.addEventListener('mouseup', this.onMouseUp);
anchor.addEventListener('mousemove', this.onMouseMove);
}
}
I used to call this.crossBrowserButton(e)
inside onMouseDown
and onMouseUp
, but I got only this.crossBrowserButton is not a function(…)
.
I think I lost this
scope some-where, but this.left
works perfectly.
Thanks in advance!
Upvotes: 1
Views: 2270
Reputation: 2799
Sounds like you did the exact opposite of what you should have done. In your original code there is a problem with the execution scope of your event listeners. They are not bound to the scope of the class and will therefore execute in the context they are run from.
Your event binding should look like this.
anchor.addEventListener('mousedown', this.onMouseDown.bind(this));
anchor.addEventListener('mouseup', this.onMouseUp.bind(this));
anchor.addEventListener('mousemove', this.onMouseMove.bind(this));
Upvotes: 2
Reputation: 1131
Okay, I figured it out: I bound this
to document.body in event and then - I took this this
in method.
Thanks for reviews. Good night folks!
Upvotes: 0