Implementing Element.hasEvent in MooTools 1.2.3

By  on  

MooTools allows you to easily add event listeners to elements using the addEvent and removeEvent methods. One thing MooTools doesn't have is a hasEvent method which will check an element's list of listeners to see if the element has been assigned a specific function per event. I experimented with implementing this functionality and believe I've found the best solution.

The MooTools JavaScript

Element.implement({
	hasEvent: function(eventType,fn) {
		//get the element's events
		var myEvents = this.retrieve('events');
		//can we shoot this down?
		return myEvents && myEvents[eventType] && (fn == undefined || myEvents[eventType].keys.contains(fn));
	}
});

The code is quite short. I can't provide a great use case for implementing this in the MooTools Core but it's a lovely little snippet to have at your disposal.

Recent Features

  • By
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • By
    Create Spinning, Fading Icons with CSS3 and MooTools

    A goal of my latest blog redesign was to practice what I preached a bit more;  add a bit more subtle flair.  One of the ways I accomplished that was by using CSS3 animations to change the display of my profile icons (RSS, GitHub, etc.)  I...

  • By
    jQuery Comment Preview

    I released a MooTools comment preview script yesterday and got numerous requests for a jQuery version. Ask and you shall receive! I'll use the exact same CSS and HTML as yesterday. The XHTML The CSS The jQuery JavaScript On the keypress and blur events, we validate and...

Discussion

  1. anything related with Jquery? i’ve looking for this so much time…

  2. Hey cool one, I admit I had wished I had such a function a few times

  3. You need to check that the retrieved events storage isn’t undefined when no events at all are defined. “retrieve” only returns a default object if one is provided using the second parameter.

    var myEvents = this.retrieve('events');
    return myEvents && myEvents[eventType] && (fn == undefined || myEvents[eventType].keys.contains(fn));
    

    Generally it’s a good idea to apply “tell, don’t ask” pattern. But if you’re making plugins that should operate together with other implementations it can be really useful to check for the existence of subscribers to ensure compatibility.

  4. Awesome. I made one myself a while back (before 1.2.3)

    Native.implement([Element, Window, Document, Events], {
        /*
            used to check if a type of event has been set
        */
        hasEvent: function(type) {
            try {
                var evs = this.retrieve('events', {});
                if(!evs || !evs[type])
                    return false;
                return true;
            } catch(err) {
                return $chk(this.$events[type]);
            }
        }
    });
    
  5. Blynk

    Very handy. Thanks.

  6. hey, I just needed a function to do that today and I thought “Didn’t Dave Walsh post something like that a while back?”. Bingo! Thanks a lot, saved me some time.

  7. Marcelo

    Really helpful, I was getting mad with a function giving a click event once and again to a div :S
    Thanks David!!!

  8. this is so killer.

  9. Joel

    Great stuff! I’ll be using this in my tests for assertions.

    I just realized that I needed to change:

    return myEvents && myEvents[eventType] && (fn == undefined || myEvents[eventType].keys.contains(fn)); 
    

    to

    return myEvents && $chk(myEvents[eventType]) && (fn == undefined || myEvents[eventType].keys.contains(fn)); 
    

    (I added $chk) in order to get it to work when no events are defined.

  10. Jhecht

    A use I suppose you could say for this is an idea I’ve been entertaining if I knew anyone who could help me code the core would be for a forum system highly relying on AJAX and DHTML. When you load a new link into the body, it by nature has no events caught to it, so you need to look through all links pointing to something like a forum post, etc, and add the event. but you don’t want to double up on the events, as it could become a hassle if you want to log information through ajax (… not a good idea if you ask me, but I’m sure someone would), so checking to see if it’s already got the function within its events would be an awesome sort of thing to do.

    Just a thought. Pretty sure someone else will poke HUGE holes in my logic here.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!