Skip to content

Instantly share code, notes, and snippets.

@keyvanakbary
Last active August 29, 2015 14:02
Show Gist options
  • Save keyvanakbary/487620891518c38ba927 to your computer and use it in GitHub Desktop.
Save keyvanakbary/487620891518c38ba927 to your computer and use it in GitHub Desktop.
Delicious currying
//Module with boilerplate/duplicated code
var Module = function (elements) {
var
onLink1Click = function (callback) {
elements.link1.on("click", function (e) {
callback();
e.preventDefault();
});
},
onLink2Click = function (callback) {
elements.link2.on("click", function (e) {
callback();
e.preventDefault();
});
};
return {
onLink1Click: onLink1Click,
onLink2Click: onLink2Click
};
};
//Extracted duplicity
var Module = function (elements) {
var
onClick = function (elem, callback) {
elem.on("click", function (e) {
callback();
e.preventDefault();
});
},
onLink1Click = function (callback) {
onClick(elements.link1, callback);
},
onLink2Click = function (callback) {
onClick(elements.link2, callback);
};
return {
onLink1Click: onLink1Click,
onLink2Click: onLink2Click
};
};
//Curry, even better!
var Module = function (elements) {
var
onClick = function (elem) {
return function (callback) {
elem.on("click", function (e) {
callback();
e.preventDefault();
});
};
},
onLink1Click = onClick(elements.link1),
onLink2Click = onClick(elements.link2);
return {
onLink1Click: onLink1Click,
onLink2Click: onLink2Click
};
};
//Usage
var module = Module({
link1: $('#link1'),
link2: $('#link2')
});
module.onLink1Click(function () {
console.log('click1');
});
module.onLink2Click(function () {
console.log('click2');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment