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.
You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.
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.
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.
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!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With