0

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);
        });
    }
1
  • Assign this to another variable outside callbacks Commented Mar 22, 2017 at 5:26

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The scope of this is always the current execution context. For arrow functions, this is lexical and adopted from the this of the execution context in which they are defined.
0

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.

6 Comments

@PardeepJain Y so?
this will refer to the gkm.events.on function instance thats y this will not work according to me
can i use self.keyscount anywhere as global?
@praveenkumars not anywhere only inside the method it is defined.
@jyithi I found a complete solution using arrow function allows to use this inside jsfunction
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.