javascript - Losing this reference in $scope.$on event -


i'm registering "$routechangesuccessevent" angularjs setting callback function. when event raised can not access controllers instance "this". current instance unedfined.

my complete typescript code:

export class ctlr {      static $inject = ["$rootscope","$route"];      constructor(private $scope: ng.irootscopeservice) {         this.scope = $scope;         this.title = "";         //this.scope.$on("$routechangesuccessevent", this.onroutechangestart);         this.registerevents();         }     private registerevents(): void {         this.scope.$on("$routechangesuccessevent",(event: ng.iangularevent, args: any) => {         //this undefined             console.log(this);         });     }     public scope: ng.iscope;     public title: string;      public onroutechangestart(event: ng.iangularevent, args: any) {         //this undefined         this.title = args.$$route.name);     }  } 

}

i'm able access of title property with:

 private registerevents(): void {         var ref = this.title;         this.scope.$on("$routechangesuccessevent",(event: ng.iangularevent, args: any) => {             ref = args.$$route.name;         });     } 

but that's not real solution because angularjs doesn't update view. seems didn't catch right reference. if thats not possible whole angularjs events seems not useabel - can't possible?

i didn't find topic strange behavior. there solution issue?

the scope changes when callback fired, why this becomes undefined.

your other example of doing:

var ref = this.title; 

actually creates -copy- of title primitive type (string). why didn't work either. updating ref not update this.title.

the usual solution this, start definition as:

var vm = this;  ... private registerevents(): void {     this.scope.$on("$routechangesuccessevent",(event: ng.iangularevent, args: any) => {     //this undefined         console.log(vm);     }); } 

so rather using this everywhere, use vm. note vm can named whatever want. important part capture reference this in scope this want use in callback. works because this not primitive type, object , rather taking copy, takes reference.

your other option use bind can apply function, function tells javascript this equate to. e.g.

$scope.$on("someeventhere", somecallbackfunction.bind(this)); 

it's matter of preference use here see people using var = this; method.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -