Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 424
Peter Lyons Avatar asked Dec 19 '12 00:12

Peter Lyons


People also ask

What can I use instead of event preventDefault?

You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.

What is event preventDefault () for?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

How do you know if an event preventDefault is used in an element?

We can use the event. defaultPrevented property in the event object. It returns a boolean indicating if the event. preventDefault() was called in a particular element.


1 Answers

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!
}
like image 90
Lukas Avatar answered Sep 28 '22 10:09

Lukas