10

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274

2 Answers2

10

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!
}
Lukas
  • 9,765
  • 2
  • 37
  • 45
  • That might work pretty well. Gotta manually add the cursor: pointer style it seems as the browser seems to only do that if it has an href attribute. – Peter Lyons Dec 19 '12 at 22:17
  • Yeah. I've never understood why browsers do that. – Lukas Dec 19 '12 at 23:01
  • 3
    Set `href` equal to `javascript:void(0);`. This will give you the cursor and keeps the `a` as a link. – Jim Buck Jul 26 '13 at 13:41
  • 1
    If you are concerned with pages reporting "Content-Security-Policy" (CSP) avoid the "javascript:" links. They may also violate http/https strictness. See https://en.wikipedia.org/wiki/Content_Security_Policy – ledlogic Mar 28 '16 at 23:32
-1

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 '#'.

biril
  • 1,975
  • 1
  • 19
  • 30
  • 2
    This is me, many years after posting this answer. Since then, it seems like it's been downvoted a few times. Mysteriously. As in, there's no comment offering any sort of explanation of why this is not an appropriate answer. Maybe it isn't, but I (and everyone else) have no way of knowing. Which is quite counter-productive and not helpful to anyone. I would appreciate any future downvoters to be helpful by offering a short rationale. Cheers :) – biril Sep 26 '16 at 11:34