Reza
Reza

Reputation: 19843

How to add another argument to a javascript callback

I have these methods

function successHandler(result/*,deferred*/) {
    var strResult = "";
    if (typeof result === 'object') {
        strResult = JSON.stringify(result);
    } else {
        strResult = result;
    }
    var mes = "SUCCESS: \r\n" + strResult;
    NotificationService.alert(mes, "پيغام", "تاييد");
    //deferred.resolve();
}

function errorHandler(error/*,deferred*/) {
    var mes = "ERROR: \r\n" + error;
    NotificationService.alert(mes, "خطا", "تاييد");
    //deferred.reject();
}

function init() {
    //var deferred = $q.defer();
    inappbilling.init(successHandler, errorHandler, { showLog: true });
    //return deferred.promise;
}

I need to create a deffer object and pass it to the success and error handler (like what I commented), since the callbacks have another argument by default I am really confused how to do that

Upvotes: 0

Views: 29

Answers (2)

Amadan
Amadan

Reputation: 198324

inappbilling.init(
  function(result) { successHandler(result, deferred) },
  function(error) { errorHandler(error, deferred) },
  { showLog: true }
);

Your deferred will be captured in the little closure, and your handlers will be called with the proper arguments.

Upvotes: 1

doldt
doldt

Reputation: 4506

You can wrap your handlers in an anonymous function, and capture the reference to deferred in its closure, like this:

inappbilling.init(
    successHandler,
    function(error){ errorHandler(error,deferred); },
    { showLog: true }
);

I'm not sure whether this is a good pattern you're trying to implement, but the above method should achieve what you're looking for.

A benefit of this is that the interface towards your error handler doesnt change (in the above case, only one param, the error object), but internally you're using your multi-param handler.

Upvotes: 1

Related Questions