Reputation: 1785
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.
Upvotes: 2
Views: 62
Reputation: 33833
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)));
};
Upvotes: 3