Giter Site home page Giter Site logo

sebastien-p / jquery.haseventlistener Goto Github PK

View Code? Open in Web Editor NEW
44.0 4.0 9.0 337 KB

hasEventListener is a jQuery plugin which checks if an Object or a DOM element actually has a particular/live/delegated event listener bound to it.

JavaScript 100.00%

jquery.haseventlistener's Introduction

hasEventListener plugin for jQuery 1.2.3 to 1.6.4

Description

hasEventListener is a (about 2.2kB minified and 1kB gzipped) jQuery plugin which checks if an Object or a DOM element actually has a particular/live/delegated event listener bound to it. More infos ?

As a bonus, hasEventListener also exposes two new jQuery methods called getEventsData whose can be used as a 1.2.3 to 1.6.4 compatible way to get events data internally stored on an element by jQuery (please, see related examples and API/documentation below).

Why ?

jQuery allows us to bind event handlers on Objects and DOM elements but doesn't provide any way to easily check if they already have one, so I first started searching over the Internet for an existing solution and saw that some people (for example here, here or even there) asked for it too.

Some people do something like $("#some_element").unbind("click").bind("click", function () {}); which works but is unclean and calls the unbind method even when not needed. I couldn't rely on that. I also found out a few existing plugins but wasn't satisfied with any of them because they lacked some important features or backward compatibility.

That's why I decided to write my own and how hasEventListener was born ...

Feedback wanted !

If you like hasEventListener, use it on a daily basis, found some bug(s), have some feature request(s), please tell me !

Contact me via Twitter or use Github's dedicated contact/report forms.

You are a developer and can improve hasEventListener by yourself ?

Go ahead, it could save me a lof of time ! Feel free to fork it, send me your work or a pull request on Github or whatever ...

Demo (outdated)

A quick demo that you even can play with is available here on jsFiddle.

Setup (HTML5 not required)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>Page title</title>
    </head>
    <body>
        <!-- Some HTML tags -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
        <script scr="jquery.hasEventListener-2.1.0.min.js"></script>
        <!-- Some other jQuery plugins and/or scripts, order matters ! -->
    </body>
</html>

API/Documentation

tested: (DOM Element or plain Object) where to check event presence for.
mode: (String, "/!(delegat|liv)e/") if the event was bound using one of these jQuery methods.
type: (String, "/[a-z_]+/") type of the event to test presence for. e.g. "click"
namespace: (String, "/\.[^\s]+/") namespace of the event to test presence for. e.g. ".namespace".
handler: (Function) event handler to test presence for.
element: (DOM Element/Window or plain Object) where to get the events data.
key: (String) type of the event data to get.
  • jQuery.hasEventListener(tested, [mode][type][namespace], [handler]) --> Boolean.
  • :hasEventListener[([mode][type][namespace])] Selector --> jQuery object.
  • .hasEventListener([mode][type][namespace], [handler]) --> jQuery object.
  • jQuery.getEventsData(element, [key]) --> Object or undefined.
  • .getEventsData([key]) --> Object or undefined.

Important notes :

  • jQuery has support for live events since 1.3.0 and for delegated ones since 1.4.2.
  • handler used with mode currently only works with jQuery 1.4.2+ (see this Fiddle).
  • tested can't be a jQuery object (see examples below).

Examples/Usage

  • $.hasEventListener($("#tabs li")[0], "!delegate click.tab_widget"); returns true or false.
  • $("#tabs li:hasEventListener(!delegate click.tab_widget)"); returns a jQuery object.
  • $("#tabs li").hasEventListener("!delegate click.tab_widget"); returns a jQuery object.
  • $.hasEventListener($("span")[0], "!live"); returns true or false.
  • $("span:hasEventListener(.my_namespace)"); returns a jQuery object.
  • $("span").hasEventListener("!live .my_namespace"); returns a jQuery object.
  • $.hasEventListener($({}).bind("custom_event", function () {})[0], "custom_event"); returns true.
  • $({}).bind("custom", function () {}).hasEventListener("custom"); returns a jQuery object.
  • $.getEventsData(window, "scroll"); returns an object or undefined.
  • $("*").getEventsData(); returns an object or undefined.

ChangeLog

  • 2.0.4 : Fix #3 (IE compat. issue)
  • 2.0.3 : Checking on plain objects and delegated events bugs corrected.
  • 2.0.2 : Custom events checking bug corrected.
  • 2.0.1 : Major Internet Explorer compatibility changes.
  • 2.0.0 : Complete rewrite, new API, please forget about anterior versions.

2.1.0 Backlog

  • API changes : !mode will be mode!, toggle and hover shortcuts will be added.
  • Add jQuery 1.7+ support

They use and/or talked about hasEventListener

Special thanks

Licence

Copyright (c) 2012 Sebastien P.

http://twitter.com/_sebastienp

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

jquery.haseventlistener's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

jquery.haseventlistener's Issues

HasEventListener will always return false in IE 7

HasEventListener will always return true do to a IE 7 bug in the get_valid_types_first_letter method. The bug is due to IE 7's short coming of not being able to index strings like arrays. So this line:

var first_try = (/Object|(Ele|Docu)ment|Window/.exec(Object.prototype.toString.call(object)) || [""])[0][0],

needs to be this line:

var first_try = (/Object|(Ele|Docu)ment|Window/.exec(Object.prototype.toString.call(object)) || [""])[0].charAt(0),

If you wanna support IE 7.

feature request - live events

Changed:
first_div = divs.eq(0).click(function (e) {

    window.alert(e.type);

}),

To:
first_div = divs.eq(0).live('click',function (e) {

    window.alert(e.type);

}),

In the JS fiddle, and it turned a 'true' to a 'false'

hasEventListner will not work in JQuery 1.8+ (possible fix for that)

Me again...

The reason for the break is that in JQuery 1.8+ they moved the $.data("events") to $._data('events") as to not mess with someones data-events tag.

I made a quick fix to this by adding a null colace in the get_events_data method on the return line to use
javascript $["_"+DATA](element, EVENTS) if javascript $[DATA](element, EVENTS) doesn't return anything.

compatibility.get_events_data = ($.now && !$.sub) ? function (element) { // 1.4.3 and 1.4.4

        // Workaround for '$({}).bind("event", handler).data("events"); // undefined' bug (on "window" too) !
        var element_type = get_valid_types_first_letter(element),
            data = $[DATA](element, ((element_type = (element_type === "W") || (element_type === "O"))) ? "__" + EVENTS + "__" : EVENTS);

        return ((data && element_type) ? (data || {})[EVENTS] : data);

    } : function (element) {

        return $[DATA](element, EVENTS) || $["_"+DATA](element, EVENTS);

    };

With this change the path we're using $("~selector").hasEventListner('event.namespace') works great.

Thanks,

Zack

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.