Search code examples
javascriptangularjsstrict

How to find function caller while in strict mode


I have a function, getGames(), in my Angular controller which can be called by both my init() function and an update() function. I need to know whether init() or update() called this function because I treat each situation differently.

I tried to access arguments.callee.caller.toString(), but this is not allowed while in strict mode, which is a requirement for this project.

How could I access the caller of getGames() while in strict mode?

My current structure below. Obviously loadingGames.promise within updateSchedule() does not work because that promise was already resolved when init() ran. I'm struggling to refactor this so that init() and updateSchedule() each depend on a different promise resolution with regard to the same function, getGames().

var loadingGames = $q.defer();

var getGames = function() {
  playersService.getGames({
    playerId: playerId
  }).$promise.then(function(data) {
    vm.games = data;
    loadingGames.resolve();
  });
};

var init = function() {
  getGames();
}

init();

var updateSchedule = function() {
  getGames();
  loadingGames.promise.then(function() {
    populateOptions(vm.games);
    vm.tableParams.reload();
  });
};

My thought was to determine the caller at the end of getGames() then resolve a different promise based on who the caller was.


Solution

  • Your getGames()-function could return a promise that is resolved as soon as the games have been fetched from the server(to make my example code shorter I left out the parameter to the service and assumed that it returns a promise):

    var games; //This is vm.games in your case
    
    (function fetchGames() {
        games = playersService.getGames()
            .then(function(data){
                games = data;
                return data;
            });
    })();
    
    function getGames() {
        return $q.when(games);
    }
    
    function updateSchedule() {
        getGames()
            .then(function(theGames){
                populateOptions(theGames);
                tableParams.reload();
            });
    }
    

    $q.when(x) returns a promise that is immediately resolved with x if x is not a promise. If x is a promise, it returns x directly.

    Just a note: Your populateOptions and tableParam.reload functions look a lot like you do manual DOM-stuff. This is almost always wrong in angular - let data binding do that job for you.