標籤:blog ar io sp java on 資料 div log
jquery外掛程式是什嗎??這裡以討論實力方法為主,比如 $("div").pluginname({});
他的最簡單形勢應該是
$.prototype.plugin = function(){}
我們一點點來加東西
1,自己的變數不汙染全域,別人的變數不汙染我們
(function($,undefined){var window = Function("return this")();//一定是window$.prototype.plugin = function(){ } )(jQuery)
2,判斷已載入或者處理其他附加資料,處理參數,執行個體化一個對象,執行個體化的方式不一定要new一個,你喜歡也可以拷貝一個,工廠一個等。。
function plugin(element, options) { var self = this; self.element = element; self.$element = $(element); if (typeof options == "object") { self.opts = $.extend({}, defaults, options); } } $.fn[pluginName] = function (options, callback) { var dataname = "plugin_" + pluginName; $(this).each(function (index, item) { var hasObject = $(item).data(dataname); if (!hasObject) { var someobj = new plugin(item, options); $(item).data(dataname, someobj); } }); } return $.fn[pluginName];
3,AMD CMD載入
// 全域模式 var pluginobj = factory(jQuery); //UMD if (typeof exports === ‘object‘) { module.exports = pluginobj; } //AMD if (typeof define === "function" && define.amd) { define(pluginName, ["jquery"], function () { return pluginobj; }); } //CMD if (typeof define === "function" && define.cmd) { define(pluginName, [‘jquery‘], function (require, exports, module) { var $ = require(‘jQuery‘); module.exports = pluginobj; }); }
全域模式是否開放取決於你的依賴項是否必然載入。
此時把原來的自執行外面再套一層,把原來的自執行改成普通方法改名為factory方法。
完整版:
(function () { var window = Function("return this")(); var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../.."; var pluginName = "mypluginname"; function factory($) { "use strict"; if ($.isFunction($.fn[pluginName])) { return $.fn[pluginName]; } function plugin(element, options) { var self = this; self.element = element; self.$element = $(element); if (typeof options == "object") { self.opts = $.extend({}, defaults, options); } } $.fn[pluginName] = function (options, callback) { //something like old jquery plugin var dataname = "plugin_" + pluginName; $(this).each(function (index, item) { var hasObject = $(item).data(dataname); if (!hasObject) { var someobj = new plugin(item, options); $(item).data(dataname, someobj); } }); } return $.fn[pluginName];; } var loaded = false; //UMD if (typeof exports === ‘object‘) { module.exports = factory(); } //AMD if (typeof define === "function" && define.amd) { define(pluginName, ["jquery"], factory); loaded = true; } //CMD if (typeof define === "function" && define.cmd) { define(pluginName, [‘jquery‘], function (require, exports, module) { var $ = require(‘jQuery‘); module.exports = factory($); }); } // other if (!jQuery.xxx && jQuery.loadScript) { $.loadScript("/scripts/plugins/xxx.js", function () { pluginobj = factory(jQuery); }) } if (!loaded) { // 全域模式 也可以不判斷強制載入是執行一遍全域模式 factory(jQuery); }})();
jquery外掛程式編寫模版