Jquery插件 - 公共方法结构

时间:2015-09-07 09:34:15

标签: jquery jquery-plugins

这是我的jquery插件的结构。 我想知道如何将我的代码更改为从插件外部调用函数(stopEvent和startEvent)

;(function ($, window, document, undefined) {

 /* Function-level strict mode syntax */
'use strict';

/* MYPLUGIN */
$.fn.myPlugin = function(options) {
    var options = $.extend({}, $.fn.myPlugin.defaults, options);

    return this.each(function() {

        var $this = $(this);
        var that = this;

        //append overlay div
        $(that).append("<div class=\"btn-overlay\"></div>");

        $(that).on('click', function() {
            startEvent();
            setTimeout(function() {
                endEvent();
            }, 2000);
        });

        function startEvent() {
            //code
        }

        function endEvent() {
            //code
        }

    });
};

/* PLUGIN DEFAULTS PARAMETERS */
$.fn.myPlugin.defaults = {
    //defaults
};

})(jQuery, window, document);

以这种方式打电话

$('div').myPlugin();
$('div').myPlugin(startEvent);
$('div').myPlugin(stopEvent);

或以这种方式打电话

var plg = $('div').myPlugin();
plg.startEvent();
plg.stopEvent();

我想知道两种调用方法的区别。 感谢

1 个答案:

答案 0 :(得分:0)

这是我认为最适合您的结构:

  ;(function($,window,document,undefined) {

    var Plugin = function(elem, options) {
        this.elem     = elem;
        this.$elem    = $(elem);
        this.options  = options;
        this.metadata = this.$elem.data('plugin-options'); //Support for inline settings.
    };
    Plugin.prototype = {

        //default options:
        defaults: {}, 

        //Build:
        init: function() {
            //Store finall options - support for recursive extend:
            this.config = this.config = $.extend(true, {}, this.defaults, this.options, this.metadata);
            return this;
        }

        //methods:
        methods: {
            _method1 : function(){},
            _method2 : function(){}
        }
    };
    //Expose defaults:
    Plugin.defaults = Plugin.prototype.defaults;
    $.fn.plugin= function(options) {

       //Append public methods:
       this.method1  = function() {
           this.each(function(i,e) {
               $(e).data('plugin').methods._method1();
           });
       };

       //Support multi elements and add the indtance to data:
       return this.each(function() {
           if ( undefined === $(this).data('plugin') ) {
               var plugin = new Plugin(this, options).init();
               $(this).data('plugin', plugin);
           }
       });

    };

  });

将实例保存到元素data后,方法可用。

此部分将您想要轻松访问的方法挂钩:

//Append public methods:
this.method1  = function() {
   this.each(function(i,e) {
       $(e).data('plugin')._method1();
   });
};

结果是:

$('ele').plugin(options);

//methods:
$('ele').plugin.method1();