简体   繁体   中英

Calling a function in a jquery plugin

I am trying to get the object of a jquery plug in I'm making use of. I want to eventually be able to add features to the plugin to suit my needs. I am currently having a problem with calling one the functions I defined in the plug in. Here is the skeleton of the code I have:

;(function($) {
      $.fn.myPlugin = function(o) {
                    .//Implementations here
                    .
                    .
            var Ex =  function(e){
                    //implementations here
            };

      }; 

})(jQuery);

The reason I want this function inside is because I want access to some of the variables defined. I would like be able to call function Ex from my html file but whatever I tried so far hasn't worked. An example of what I have tried is:

$.fn.myPlugin.Ex("x");

No return statement anywhere. I'm not great at javascript or jquery but I'm trying to learn. Any help in explaining what I'm doing wrong is appreciated.

Your plugin design pattern is wrong.

To achieve what you want, you can use this common one :

;(function($){
  var methods = {
     init: function() {
       //stuff
     },
     function1: function() {
       //stuff
     },
     function2: function(opt) {
       //stuff
     }
  };
  $.fn.myPlugin= function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments,1));
    } else if (typeof method === 'object' || ! method) {
      return methods.init.apply(this, arguments);
    } 
  };
})(jQuery);

With this structure :

$.fn.myPlugin(); will call init()

$.fn.myPlugin("function1"); will call function1()

$.fn.myPlugin("function2",option_exemple); will call function2(opt)

Disclaimer : I use this very often, but it's not mine. Can't remember where I found it*.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM