Reputation: 325
this
variable is not accessible outside js methods or packages in angular2 typescript.
public mousekeyAction() {
var mc=0,kc=0;
gkm.events.on('key.pressed', function (data) {
this.keyscount= kc++;
console.log(this.keyscount);
});
// Listen to all mouse events (click, pressed, released, moved, dragged)
gkm.events.on('mouse.*', function (data) {
this.mousecount=mc++;
console.log(this.mousecount);
});
}
Upvotes: 0
Views: 138
Reputation: 10292
Assign this
to another variable as below
public mousekeyAction() {
var mc = 0,
kc = 0,
self = this;
gkm.events.on('key.pressed', function(data) {
self.keyscount = kc++;
console.log(self.keyscount);
});
// Listen to all mouse events (click, pressed, released, moved, dragged)
gkm.events.on('mouse.*', function(data) {
self.mousecount = mc++;
console.log(self.mousecount);
});
}
Since callback
context is different from context of expected this
.
Upvotes: 0
Reputation: 86800
you have to use fat arrow
as function/callback instead of simple function. this will maintain the scope of this even outside the function too.
Use your function like this :-
public mousekeyAction() {
var mc=0,kc=0;
gkm.events.on('key.pressed', (data) => {
this.keyscount= kc++;
console.log(this.keyscount);
});
// Listen to all mouse events (click, pressed, released, moved, dragged)
gkm.events.on('mouse.*', (data) => {
this.mousecount=mc++;
console.log(this.mousecount);
});
}
for more info refer here
Upvotes: 1