Reputation: 1398
I am getting to know jQuery a little bit more. I recently created a plugin (works just fine). However, here it something that I am curious about. Suppose I have the following plugin ...
(function($){
$.fn.plugin = function(){
//code here
};
}(jQuery));
then if I use it $('#selector').plugin()
and then use it again $('#selector').plugin().method1()
it seems to create two different instances.
How can I modify my code so it still refers to the same instance given that the selector is the same, something similar to the following behaviour?
var pg = $('#selector').plugin();
pg.method1();
Thanks!
Upvotes: 4
Views: 5161
Reputation: 7688
It is not possible without creating an instance object. You need to create instance object. But there is a way which will give you direct calling a function without creating instance. create your plugin as a javascript object which holds functions. and then you can call your methods inside your plugin.
Here is an example
$.fn.plugin = {
con:function(val){
console.log(val)
}
}
$("body").plugin.con("ok");
Upvotes: 0
Reputation: 12452
(function($){
$.fn.plugin = function(){
return {
method1 : function(text){
console.log(text);
}
}
};
}(jQuery));
var smth = $(document).plugin();
smth.method1('text this');
Here is a working fiddle : http://jsfiddle.net/sazv3dge/
Upvotes: 1