2

I am wondering how callbacks works in angularJS. I have this code working perfectly like this

$scope.loginFB = function () {
  hello(FACEBOOK).login(function () {
    hello(FACEBOOK).api('me').then(function (profile) {
      console.log('successful api call');
      dbService.handle_credentials(profile);
      $rootScope.$apply(function () {
        $location.path('/homePage');
      });
    }, function(){
      console.error('something went wrong with authentification');
    });
  });
};

but works in weird way when refactored like this

$scope.loginHandler =function () {
  hello(FACEBOOK).api('me').then(function (profile) {
    console.log('successful api call');
    dbService.handle_credentials(profile);
    $rootScope.$apply(function () {
      $location.path('/homePage');
    });
  }, function(){
    console.error('something went wrong with authentification');
  });
};

$scope.loginFB = function () {
  hello(FACEBOOK).login($scope.loginHandler());
};

please tell me what i am doing wrong with this refactoring.

0

1 Answer 1

3

By including the params, you are immediately invoking your function callback rather than passing a function reference, which is what you really want to do.

$scope.loginFB = function () {
    hello(FACEBOOK).login($scope.loginHandler);
};

If you want to pass a parameter to your callback function, you can use one of two approaches.

Wrap your callback in an anonymous function

$scope.loginFB = function () {
    hello(FACEBOOK).login(function() { return $scope.loginHandler(param); });
};

In a modern browser, use .bind().

$scope.loginFB = function () {
    hello(FACEBOOK).login($scope.loginHandler.bind(this, param)));
};
Sign up to request clarification or add additional context in comments.

1 Comment

but what is i want to send parameter to the function. imagine i want to call $scope.loginHandler(param), how do i do that ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.