1

This should be an easy one :)

I want to add a click event listener only in case it hasn't been added earlier already, and prevent it from running twice. I thought of accomplishing this like so:

HTML

<a href="http://www.google.com"> Google is your friend </a>
<a href="http://www.Bing.com"> Bing's alright as well </a>

JS

var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++)
{
    if (*Default has been prevented for links[i]*){ //how do I implement this check?
        return; //do nothing, we're all done.
    } else {
        links[i].addEventListener("click",function(event){
            event.preventDefault();
            alert("Showing you this instead of opening this link!"); 
        });
    }
}

In my real world case the added event listener is preventing the default behavior. So how can I check if it has been prevented before? I want to make sure the listener won't be added twice. How can I implement this check?
Many thanks for any ideas.

user1555863
  • 2,567
  • 6
  • 35
  • 50
  • 1
    Use event delegation instead. – SLaks Aug 13 '13 at 14:52
  • Not adding the listener twice can be achieved by not adding the listener twice – Esailija Aug 13 '13 at 15:03
  • Well, obviously enough, yeah. But this is a rather simplified example of what is happening in my project, so it we'll be readable. I just thought to try and tackle this problem from this angle. – user1555863 Aug 13 '13 at 15:07

1 Answers1

0

You can achive your goal using object identity. Quote from MDN:

Multiple identical event listeners

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.

Example:

// the "one" handler function instance
var theEventPreventDefaultHandler = function (event) {
    event.preventDefault();
};

var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener("click", theEventPreventDefaultHandler);
}

Watch the Fiddle.

I didn't check that out, but it could be possible the addEventListener function returns false to catch the case, when it didn't add a "duplicate". It doesn't, returns only undefined.

To "check if an event has a handler" is not supported natively. It is possible in jQuery, because this manages the handlers in a .data("events") array, also to support IE's old quirks behaviors in this and window.event. That said, it would be a pain in the ass to reimplement what ejohn did. There about are a bunch of questions on stackoverflow:

Community
  • 1
  • 1
metadings
  • 3,798
  • 2
  • 28
  • 37