Search code examples
backbone.jsanchormarionettepreventdefault

Do I always have to call preventDefault for anchor tags with href='#' in Backbone / Marionette views?


In my Backbone app I have a root route which is just blank. In some of my views I have <a> tags for UI elements that I have registered in the view's events object. In order to have properly formed markup I need to have href='#' in these anchors but I don't want them to go to the root of my app.

It seems like for all <a>s that I don't want to go to the root, I have to always call evt.preventDefault(). I would like to confirm this and find out if there are other/better options available.

I'm aware I could make a <div> or <span> with cursor: pointer but my gut is telling me I want these to semantically be anchors.


Solution

  • You have three options:

    • always return false in the handler or call preventDefault on the event
    • use href="javascript:void(0)" (which hurts my eyes)
    • place some sort of special class or data attribute on the links that you don't want to be navigable and create some generic handler that always prevents the navigation
    • use <button> whenever you are using <a> with a dummy href right now

    In my opinion, the last option is the best, because it's clear that these GUI elements perform some action that is 'local' to the content you are showing at the moment, while links (or rather: URIs they link to) are by design representing different resource (and content).