2

I have a jQuery plugin that needs to register a click event handler:

$.fn.myPlugin = function (options) {
    var settings = {
        // snipped
    };
    $.extend(settings, options || {});

    $("body").click(function () {
      // Do Something
    });

    // Rest of the plugin
});

The problem is that multiple invocations register the function more than once. Since the function needs to stay attached, I can't use .one().

Is there a way if a function is already attached? Can I give it a name or so? Or do I have to set some boolean flag using closure magic?

Michael Stum
  • 177,530
  • 117
  • 400
  • 535

3 Answers3

3

Namespace your events.

$('body').unbind('click.myPlugin').bind('click.myPlugin', function() {
   ..code...
});

More on Namespaced Events.

John Strickler
  • 25,151
  • 4
  • 52
  • 68
  • Worked like a charm! That essentially allows me to refer to my events with a name, which removes any ambiguity. – Michael Stum Nov 03 '10 at 19:14
  • Just as a reminder for the ones to follow: It's important to use click.XXX syntax to that jQuery still binds it to the click event. I used myPlugin.doClick and myPlugin.click and it didn't work. Obvious in hindsight, but caused me a few minutes of trouble :) – Michael Stum Nov 04 '10 at 00:15
1

A very easy method with good performance would be to set a data element on the body element:

if (!$.data(document.body, 'myPluginRegistered') {
    $.data(document.body, 'myPluginRegistered', true);

    // do your plugin code here
}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Just for the record, wasn't me that downvoted it. One could say it's just a fancy global variable, but it is exactly what it's supposed to be: A marker on an element. – Michael Stum Nov 03 '10 at 19:18
0

Easiest might be the boolean plus closure magic you suggested. Alternatively, you could get the list of all functions bound to "click" object, and see if the function you're attaching is there already.

This question shows how to get the list.

List all javascript events wired up on a page using jquery

Though, the namespace suggestion that came in after I first responded is probably simpler.

Community
  • 1
  • 1
morgancodes
  • 25,055
  • 38
  • 135
  • 187