Skip to content

Instantly share code, notes, and snippets.

@wayspurrchen
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wayspurrchen/b5852f9d9473c6477593 to your computer and use it in GitHub Desktop.
Save wayspurrchen/b5852f9d9473c6477593 to your computer and use it in GitHub Desktop.
Code snippet that can wrap any function and give it the ability to run a callback
var callbackCurrier = function(obj, funcName) {
var originalFunction = obj[funcName];
var callbackFunc = function() {
var args = Array.prototype.slice.call(arguments, 0);
var callback = args.pop();
var returnValue = originalFunction.apply(obj, args);
if (callback) {
callback(returnValue);
}
};
obj[funcName] = callbackFunc;
};
var localStorageInterface = {
getQuestion: function(questionId) {
return localStorage.getItem('q' + questionId);
},
setQuestion: function(questionId, value) {
localStorage.setItem('q' + questionId, value);
}
}
// This could just as easily be a loop over an object's own properties,
// with a check that they are functions. Could also loop over an array
// of strings containing the function names that should return callbacks.
// Useful for enforcing an event-driven programming model on synchronous code.
callbackCurrier(localStorageInterface, 'getQuestion');
callbackCurrier(localStorageInterface, 'setQuestion');
localStorageInterface.setQuestion("status", "true", function() {
localStorageInterface.getQuestion("status", function(data) {
console.log(data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment