4

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!

George G
  • 7,443
  • 12
  • 45
  • 59
Gacci
  • 1,388
  • 1
  • 11
  • 23
  • check this :http://stackoverflow.com/questions/18185956/calling-a-function-inside-a-jquery-plugin-from-outside – Ehsan Sajjad Oct 08 '14 at 08:16
  • Attach some data to the selected elements indicating that they have been initialised for this plugin. And test for the presence of that data before (re)initialising, thus preventing multiple initialisation when calling methods. – Roamer-1888 Oct 08 '14 at 08:18
  • Would it be possible for you to create a little sample. Thanks! – Gacci Oct 08 '14 at 16:00

2 Answers2

1
(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/

Razvan Dumitru
  • 11,815
  • 5
  • 34
  • 54
  • @Laxmikant Dange Hello, first of all thank you both for your quick replies. I think I did not explained myself effectively. What I meant is, how can I use my functions without declaring a variable to the instance outside the plugin. So I wan to be able to use my functions just like I can use jQuery functions on elements, for instance $('#div-element').width() and then I use another function on the same element $('#div-element').height(). I could also use var elem = $('#div-element'); elem.width(), elem.height() and I would still get the same behaviour. – Gacci Oct 08 '14 at 15:47
0

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");
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65