jQuery插件的开发包括两种:
一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法。jQuery的全局函数就是属于jQuery命名空间的函数;另一种是对象级别的插件开发,即给jQuery对象添加方法。
本文提供的jQuery插件开发框架综合上述两种方式,代码如下所示:
// AMD support (function(factory) { //"use strict"; if (typeof define === 'function' && define.amd) { // using AMD; register as anon module define(['jquery'], factory); } else { // no AMD; invoke directly factory((typeof (jQuery) != 'undefined') ? jQuery : window.Zepto); } } (function($) { "use strict"; var pluginNS = 'InputBox', pluginPfx = 'IP', /* ---------------------------------------- VARS, CONSTANTS ---------------------------------------- */ totalInstances = 0, /* plugin instances amount */ /* ---------------------------------------- DEFAULT OPTIONS 默认参数 ---------------------------------------- */ defaults = { nParam: 0 }, /* ---------------------------------------- METHODS 公有函数 ---------------------------------------- */ methods = { init: function(options) { var opts = $.extend(true, {}, defaults, options); /* plugin constructor */ return $(this).each(function() { $this = $(this); if (!$this.data(pluginPfx)) { /* prevent multiple instantiations */ /* store options and create objects in jquery data */ $this.data(pluginPfx, { idx: ++totalInstances, /* instance index */ opt: opts /* options */ });
var d = $this.data(pluginPfx), o = d.opt; } }); }, destroy:function(){ } }, /* ---------------------------------------- FUNCTIONS 私有函数 ---------------------------------------- */ _default = function(opts) { }; /* ---------------------------------------- PLUGIN SETUP ---------------------------------------- */ /* plugin constructor functions */ /* usage: $(selector).pluginNS(); 对象级别*/ $.fn[pluginNS] = 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); } else { $.error("Method " + method + " does not exist!"); } }; /* usage: $.pluginNS(); 类级别*/ $[pluginNS] = 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); } else { $.error("Method " + method + " does not exist!"); } }; /* allow setting plugin default options. usage: $.pluginNS.defaults.nParam=5; to apply any changed default options on default selectors (below), use inside document ready fn */ $[pluginNS].defaults = defaults; }));
上述代码参考开源项目jQuery.mCustomScrollbar插件的整理。
......