Skip to content

Instantly share code, notes, and snippets.

@Sljubura
Created February 10, 2013 17:35
Show Gist options
  • Save Sljubura/4750359 to your computer and use it in GitHub Desktop.
Save Sljubura/4750359 to your computer and use it in GitHub Desktop.
Callback pattern when passing method of an object.
// Calling callback when callback is a method of an object
var myapp = {};
myapp.elementHeight = 100;
myapp.setElementHeight = function (node) {
node.style.height = this.elementHeight;
};
// Where setElementHeight is our callback
// findNodes() function which call our callback
var findNodes = function (callback) {
if (typeof callback === 'function') {
// ... find some node
callback(foundNode)
}
};
// If we call findNodes(myapp.setElementHeight),
// it won't work as expected, because this.elementHeight will not be defined and 'this' will point to global object.
// Solution is to pass the callback and to pass the object this callback belongs to.
findNodes(myapp.setElementHeight, myapp);
// And adjusted callback caller would be:
var findNodes = function (callback, callback_obj) {
// ... find some node
if (typeof callback === 'function') {
callback.call(callback_obj, foundNode);
}
};
// If we want to avoid passing the same object twice, we could pass the method as a string.
findNodes("setElementHeight", myapp);
// Then the findNodes function would be something like this:
var findNodes = function (callback, callback_obj) {
// ... find some node
if (typeof callback === "string") {
callback = callback_obj[callback];
}
if (typeof callback === "function") {
callback.call(callback_obj, foundNode);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment