Last active
August 29, 2015 14:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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