javascriptbackbone.jsbackbone-events

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

  • 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!
    }