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.
$.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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With