简体   繁体   中英

Javascript: Setting parameters to functions that are being passed as a paramater

I have a class errorHander which has the following function defined:

function handleError(errorData, callback, message) {

I can now pass the handleError function as a parameter into functions that can take a function to handle the error message. eg:

var signboards = devicesService.query()
        .$promise.then(function success(data) {
            console.log(data);
            $scope.devices = data;
        }, errorHandler.handleError);

The callback function is run and has the first variable (errorData) set to whatever error information is returned from the server. The success function is written out in full to display the way parameters are passed.

The problem is, that I would like to set the additional parameters as defined in my original handleError function. I would like to set the callback and message parameters.

Is this at all possible?

Here's a demo in pure js but should be easy to port:

http://plnkr.co/edit/4xB5JkXPvxK4mhCW66ik?p=preview

You can do a partial-like thing with the function:

$scope.errorCallback = function(errorData, callback, message) { ... }
$scope.errorCallbackPartial = function(callback, message) {
   return function(errorData) {
       errorCallback(errorData, callback, message)
   }
}

So in your example errorHandler.handleError with errorHandler.errorCallbackPartial(someCallback, someMessage), where the callback and message are written by you. Then it will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM