Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare callback like Parse does?

Usually, I declare a function with success and fail callbacks as follow

function yoyoyo(param, successCallback, failCallback) {
  // do something with param
  // ...
  if (success) {
    successCallback('success');
  } else {
    failCallback('fail');
  }
}

then I will use it like this

yoyoyo('abc', function(success) {
  console.log(success);
}, function(err) {
  console.log(err);  
});

BUT, when I look into Parse Javascript Guide, they guide me to use the function like this (i.e. merge success and fail callbacks in one object?)

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
  success: function(gameScore) {
    // The object was retrieved successfully.
  },
  error: function(object, error) {
    // The object was not retrieved successfully.
    // error is a Parse.Error with an error code and message.
  }
});

How can I declare my function with success and fail callbacks like parse does?

like image 316
Calvin Chan Avatar asked Jan 07 '23 21:01

Calvin Chan


1 Answers

You would just change your function to accept a callbacks arg (call it whatever you want) and then access the handlers off that object:

function yoyoyo(param, callbacks) {
  // do something with param
  // ...
  if (success) {
    callbacks.success('success');
  } else {
    callbacks.error('fail');
  }
}

then you would call it with:

yoyoyo('abc', {
    success: function(status) { 
    },
    error: function(status) {
    }
});

Note though, that your code should check to ensure that the object passed in has both of the methods before attempting to call them.

like image 168
mcgraphix Avatar answered Jan 15 '23 21:01

mcgraphix