Skip to content

Instantly share code, notes, and snippets.

@db-roberto
Created January 29, 2014 23:01
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 db-roberto/8699085 to your computer and use it in GitHub Desktop.
Save db-roberto/8699085 to your computer and use it in GitHub Desktop.
// partial application in javascript
// paste this code into your console and try it on this page!
function image_alert( ev, number ) {
// the following line shows that the ev object is available to the callback and that the second argument is available
// second argument (number) provided through partial application
alert( "IMAGE NUMBER " + number + " CLICKED! " + ev.target.src );
}
var applied_callback = function(num) { // this function will provide a number...
return function(e) { // and return another function that will take e (event object) as a parameter...
return image_alert( e, num ); // which will do image_alert, passing the event object and the captured num value
};
};
// this works because num will be captured in the function's context on creation
// the callback will be passed the event object, and it will have the num's captured value
// the num's captured value will be partially applied to the function
// so instead of needing to pass two parameters directly to image_alert, one parameter will be fixed
var i = 0; // the number that will be applied to the callback
jQuery( 'img' ).each( function() {
i++;
// we are using jQuery for this example
// "this" in the current context refers to the img
jQuery( this ).on( 'click', applied_callback(i) );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment