javascript - How does callback work in AngularJS call to REST service? -


i studying angularjs , rest. code sample uses word callback repeatedly in authentication function. is callback keyword in javascript or angular? or callback custom variable created in code? how callback work in code below? googling callback , angularjs not producing usable results. the code angularjs module in question can read @ link, contains code sample app.

here module code itself:

angular.module('auth', []).factory( 'auth',      function($rootscope, $http, $location) {          enter = function() {             if ($location.path() != auth.loginpath) {                 auth.path = $location.path();                 if (!auth.authenticated) {                     $location.path(auth.loginpath);                 }             }                            }          var auth = {              authenticated : false,              loginpath : '/login',             logoutpath : '/logout',             homepath : '/',             path : $location.path(),              authenticate : function(credentials, callback) {                  var headers = credentials && credentials.username ? {                     authorization : "basic "                             + btoa(credentials.username + ":"                                     + credentials.password)                 } : {};                  $http.get('user', {                     headers : headers                 }).success(function(data) {                     if (data.name) {                         auth.authenticated = true;                     } else {                         auth.authenticated = false;                     }                     callback && callback(auth.authenticated);                     $location.path(auth.path==auth.loginpath ? auth.homepath : auth.path);                 }).error(function() {                     auth.authenticated = false;                     callback && callback(false);                 });              },              clear : function() {                 $location.path(auth.loginpath);                 auth.authenticated = false;                 $http.post(auth.logoutpath, {}).success(function() {                     console.log("logout succeeded");                 }).error(function(data) {                     console.log("logout failed");                 });             },              init : function(homepath, loginpath, logoutpath) {                  auth.homepath = homepath;                 auth.loginpath = loginpath;                 auth.logoutpath = logoutpath;                  auth.authenticate({}, function(authenticated) {                     if (authenticated) {                         $location.path(auth.path);                     }                 })                  // guard route changes , switch login page if unauthenticated                 $rootscope.$on('$routechangestart', function() {                     enter();                 });              }          };          return auth;      }); 

additional information:


based on @okonyk's response, including code different module calls auth.authenticate() function:

$scope.login = function() {     auth.authenticate($scope.credentials, function(authenticated) {         if (authenticated) {             //do stuff              $scope.error = false;          } else {              $scope.error = true;         }     }) } 

so how call login() auth.authenticate($scope.credentials, function(authenticated) work? function(authenticated) parameter sending boolean determines functionality inside auth.authenticate()? if so, can please explicit? can piece together. example true might indicate callback, while false might indicate note callback, have explained. you can read code in sample app other module login() method clicking on link.

here pretty explanation:

a callback function, known higher-order function, function passed function (let’s call other function “otherfunction”) parameter, , callback function called (or executed) inside otherfunction. callback function pattern (an established solution common problem), , therefore, use of callback function known callback pattern.

callback not keyword, name of parameter passed function, can call whatever want (callback or cb pretty common).

i'll try explain on example of super simplistic custom build callback function:

function useascallback(string){   console.log("callback being executed passed parameter: " + string) }  function main(param, callback){   callback(param) }  main(123456, useascallback) 

if run this, print: callback being executed passed parameter: 123456

callback pattern commonly used handle javascript asynchronous behavior.

edit: more specific example:

talking code snippet... lets you'll inject factory controller.

now have auth.authenticate method exposed. have pass 2 parameters(credentials, callback).

auth.authenticate({username: joe, password: 123456}, function(authstatus){   if(authstatus){     console.log("successfully authenticated")   }else{     console.log("access denied")   } }); 

we passed anonymous function callback parameter of our auth.authenticate method.

edit: responce 'additional information':

it looks there might misunderstanding. asking:

is function(authenticated) parameter sending boolean determines functionality inside auth.authenticate()

thing that, complete opposite: auth.authenticate() passes value 'function(authenticated)', anonymous function. happens @ point: callback && callback(auth.authenticated); - on .success or callback && callback(false); - on .error


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -