DRY up your jQuery event.preventDefault() usage
If you find that your jQuery code using event.preventDefault()
all of the time, you can DRY up that code using method combinators. There's a great library that you can use here.
How about an example:
var preventer = before(function (event) {
event.preventDefault();
alert('Preventing Default Behaviour');
});
var handleClick = function () {
alert($(this).attr("href"));
};
$("#link").click(preventer(handleClick));
So what's going on here? If you're not familiar with method combinators (aka method decorators), this might seem a little foreign to you.
The first line of code defines a new function, called preventer
, that will wrap the event.preventDefault()
in a reusable function. I added an alert
in there so that you can see where that happens in the call stack when you test it out.
You'll notice that in defining preventer
, I've used a function called before
. The before
function comes straight from the method-combinators library mentioned above. This is where the magic happens. The before
function accepts a function as a parameter and returns a new function as its result. The resulting function, in this case preventer
, itself accepts a function that is consider the main code to be run. What preventer
does is execute the function passed to before
before it runs the code passed to itself.
Once you wrap your head around that, you'll understand how the before function wraps itself around the function. I hope this is easier to understand than it was to write!
Check it out in action, with this jsFiddle