'Avoid event.preventDefault() boilerplate in backbone event handlers
I have a lot of Backbone.js actions that start with link like:
<a href="#makeCookies">Make Cookies</a>
and a Backbone.View events hash like:
'click [href=#makeCookies]': 'makeCookies'
and an event handler function like:
makeCookies: function (event) {
event.preventDefault();
//code to make cookies
//I have no intention of ever using #makeCookies in the URL,
//it's just there so I can wire up the event handler properly
}
Is there a clean way to avoid that boilerplate event.preventDefault(). I thought about just using <button> tags instead of <a> tags but that seemed inappropriate.
Solution 1:[1]
Why do you need to have the href attribute at all, if you plan on discarding it anyway? How about just using a class name?
HTML code:
<a class="makeCookies">Make Cookies</a>
View code:
'click .makeCookies': 'makeCookies'
...
makeCookies: function (event) {
// No need for event.preventDefault() anymore!
}
Solution 2:[2]
You could add a prevent-default handler to the document element. Like so:
$(document).click(function (e) {
if (e.target.tagName === "A") {
e.preventDefault();
}
})
This would of course disable all navigation initiated by a-tags but if your app provides custom handling for that then it shouldn't be a problem.
If you'd like to let some a-tags 'pass through' then you could add further conditions in the prevent-default handler, like checking if the value of the href attribute begins with '#'.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukas |
| Solution 2 | biril |
