Update view in Cordova callback


#1

Hello,

I’m using cordova.InAppBrowser and I need to close It when the url change and It contains the string “success”. It runs correctly but in the callback of the event I need to change the color of a button in the view. Here I have problems.

If I put the code this.myColor = "danger"; outside the callback it runs.

This is the code I’m using:
HTML:

  <button [color]="myColor" (click)="autDevice()">

TS:

    var ref = cordova.InAppBrowser.open(data.json().authorizationUrl, '_blank', 'location=yes');

        ref.addEventListener('loadstart', function (event) {        
          var URL = event.url;     
          if (URL.indexOf("success") >= 0) {
            console.log("SUCCESS");          
            this.myColor = "accent";
            ref.close();
          }
          if (URL.indexOf("access_denied") >= 0) {
            console.log("access_denied");          
            this.myColor = "danger";
            ref.close();
          }
        });

Can you help me?

Thanks
Stefano


#2

Declare your callback using the fat arrow syntax, so “this” will be bound properly.


#3

Can you help me with the arrow syntax please?

Thanks
Stefano


#4

I would recommend you to read about arrow functions (see the linked post for details).


#5

I’m using this code in SceltaDevicePage class:

     var self = this;     
     this.mget = this.http.get(url)
      .subscribe(data  => {
        
        var ref = cordova.InAppBrowser.open(data.json().authorizationUrl, '_blank', 'location=yes');
        console.log( <SceltaDevicePage>  self);
        ref.addEventListener('loadstart',  (event, self) => {
          console.log(<SceltaDevicePage> self);
//...
}

Before adding Listener self is correct but inside the callback It is undefined.
Where is the problem?

Thanks.
Stefano


#6

You’ve added it as a parameter to the callback and since the callback has no such parameter (i.e. passes no value for it) it’s becoming undefined. Remove the self parameter of the callback and it should work as expected. Although you don’t need to use self at all - when you’re using arrow functions this should work as expected and you could just replace self with this.


#8

Hi,
ok, from console log I see the correct value but the view doesn’t get updated when the value changes. Otherwise, If I click something on the view, the UI get refreshed. I’m using Ionic 2 beta 9. I read some post that It was solved with the last version of Ionic but I still have problems.