Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get plugin object reference back from element on which plugin is applied

Please consider following code. Here I have a jquery plugin myPlugin by using which I changed the ui of #targetElement

var myPluginVar = $('#targetElement').myPlugin();

I created a button and added a click event listener on it

$('#myButton').click(function(){
    // HERE I want reference of myPlugin back.
}

Now on a button trigger I want to get back myPlugin object. I don't want to use myPluginVar. Is there any way to get reference of myPlugin using element on which plugin is applied.

like image 466
Durgpal Singh Avatar asked Mar 22 '26 12:03

Durgpal Singh


2 Answers

$.fn.myPlugin = function(){} will create a plugin that can be called on an element like this: $("#example").myPlugin();, as you know.

$.myPlugin = function(){} will create a plugin that can be called statically like this: $.myPlugin();.

So all you have to do is set $.myPlugin every time you call $.fn.myPlugin so it will refer to the last element used.

$.fn.myPlugin = function(){
  this.text("Hello, world!");
  
  var t = this;
  
  $.myPlugin = function() {
    return t;
  }
};

$("#test").myPlugin();

$("#button").click(function(){
  $.myPlugin().text("something else");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
<button id="button">Click Me</button>
like image 83
Samuel Reid Avatar answered Mar 24 '26 01:03

Samuel Reid


thats depend on how you write your plugins.

following this example of basic plugin:

(function($){
    $.fn.myPlugin = function(){
        return this.text('Iam is myPlugin');
    };
}(jQuery));

thats plugin (yet) cannot be referenced, because it didn't passed their self to anything.

but if change plugin code abbove to this:

(function($){
    $.myPlugin = function(el){
        $(el).data('myPlugin', this);
        return $(el).text('Iam is myPlugin');
    };
    $.fn.myPlugin = function(){
        return new $.myPlugin(this);
    };
}(jQuery));

you can call plugin self referenced with:

$('#targetElement').data('myPlugin');

offcourse if plugin never initialized on #targetElement, it will returned as undefined

but if you have initialize #targetElement, with:

$('#targetElement').myPlugin();

it will return with $.myPlugin object

like image 20
Fal Avatar answered Mar 24 '26 00:03

Fal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!