peter.swallow
peter.swallow

Reputation: 945

Can't access local property from within Callback in Ionic2

I have a basic Ionic 2 app, which uses Angular2. I have a fairly basic but frustrating problem. Here is my component...

import {Component} from "@angular/core";

@Component({
  '<ion-content>{{id}}</ion-content>
});

export class ListPage {

    constructor(nav, navParams) {
       this.id = "123";

       //This could be any method (ajax call or just an event emitter)
       asyncMethodWithCallBack(function(result)
       {
           this.id = result; //Cannot find this.id
       }
    }
}

The problem is when my app tries to do attach itself to a method with accepts a callback, when the callback fires, it is no longer able to find the this.id scope.

I must be doing something simple here, but I don't understand the new scoping properly.

Upvotes: 0

Views: 726

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202156

You should an arrow function to be able to use the lexical this:

asyncMethodWithCallBack((result) => 
   {
       this.id = result; //Cannot find this.id
   });

Extract from MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions):

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

Arrow functions capture the this value of the enclosing context.

Upvotes: 4

Related Questions