-1

I just wrote one module like this:

(function(){
    'use strict';
    angular.module('myApp.dashboard').controller('mainControl',mainControl);

    mainControl.$inject = ['whichToShow','authService'];
    function mainControl(whichToShow,authService){
        var self=this;
        this.values=whichToShow.getVar();
        this.logOut=function(){
            whichToShow.setVar(false);
            authService.logOutUser();
        };
        this.removeEvent=function(eventId){
            authService.removeEvent(eventId);
        }

        authService.setOnAuth(authDataCallback);
        // Callback to set user's events.
        function authDataCallback(authData) {
            if (authData) {
                console.log("User is logged in with " + authData.email);
                self.eventList={};
                whichToShow.setVar(true);
            } else {
                console.log("User is logged out");
            }
        }
    }
})();

In this module the line self.eventList={};, at first I just use this.eventList={}, the console tells me TypeError: Cannot set property 'eventList' of undefined all the time.

Until I set self as this, and use self in the authDataCallback function. I finally figure it out how to solve it but don't know why is this? Could you tell me?

fourth
  • 349
  • 2
  • 3
  • 12
  • can you publish your service please ? – qchap Nov 08 '16 at 21:52
  • It has everything to do with scope -- your `authDataCallback()` method gets called from a different scope, so `this` is no longer what you thought it should be. Setting `self = this` before `authDataCallback()` gets called allows you to access the original scope. – arthurakay Nov 08 '16 at 21:52
  • 2
    There a million good resources on `this` -- but the first Google search result I found on SO was: http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – arthurakay Nov 08 '16 at 21:54

1 Answers1

1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

The this keyword in JS is context specific. Your callback has it's own execution context so this refers to that context and isn't looking in the surrounding context.

Other than assign this to a variable and puling on the variable, you can use .bind(this) to use it in the function's context or you start using ES6 fat arrow functions.

Falk
  • 577
  • 4
  • 11