Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you if check a jQuery plugin is already bound to a DOM node?

Most jQuery plugins are tied/bound to a DOM node when you first initialize them.

$('#foo').bar({options: ...});

How can you check to see what plugins or objects are currently bound to a DOM node like #foo?

if($('#foo').bar)
if($.inArray('bar', $('#foo').eq(0)))
if($('#foo').eq(0).indexOf('bar'))
if($('#foo').hasOwnProperty('bar'))

For example, it's possible to get the events bound to an object like this

console.log($('#foo').data('events'));
like image 921
Xeoncross Avatar asked Oct 30 '12 16:10

Xeoncross


2 Answers

Unless the plugin itself defined some way of altering the element(s) it's working on, it's not possible. For example:

$.fn.extend({
  foo: function() { console.log("I am foo!"); }
});

$('#bar').foo();

Here I defined a complete (well, more-o-less) jQuery plugin which doesn't even try to interact with its calling element. Still, you can use it as you wish, on any jQuery-wrapped collection of elements, as any jQuery-wrapped collection of elements has this method in its prototype because of this line (from jquery.js):

jQuery.fn = jQuery.prototype = { ... }

... after $.fn.extend was called to plug in that plugin, no pun intended.

But even if my plugin were required to change its calling element in some way, like this:

$.fn.extend({
  bar: function() { this.html('I am all bar now!'); }
});
$('#bar').bar();

... I would still need to, basically, handle this with some external events (DOM Mutation ones), and not just depend on some internal jQuery logging.

like image 156
raina77ow Avatar answered Sep 23 '22 18:09

raina77ow


In my case, the plugin I was attempting to detect happens to add some data to the elements $(element).data() store. I've also seen plugins add classes or ID's with either their name - or alterations of their name in them.

Below is the code I am currently working with to solve this problem. Probably don't work for most plugins though.

$.fn.extend({
    isPluginBound: function(pluginName)
    {
        if(jQuery().pluginName)
        {
            var name = pluginName.toLowerCase();

            return this.data(pluginName) || this.data(name)
                || this.attr('class').toLowerCase().indexOf(name) !== -1 // vs hasClass()
                || this.attr('id').toLowerCase().indexOf(name) !== -1;
        }
    }
});

To use it just call $('#foo').isPluginBound('bar');

like image 27
Xeoncross Avatar answered Sep 24 '22 18:09

Xeoncross