1、典型的插件开头写法
;(function (a) {
"use strict";
if ("function" === typeof define && define.amd)
define(["jquery", "moment", "commonMethod"], a);
else if ("object" === typeof exports)
module.exports = a(require("jquery"),require("moment"));
else {
if ("undefined" === typeof jQuery) throw "Dropdown requires jQuery to be loaded first";
if ("undefined" === typeof moment) throw "Dropdown requires Moment to be loaded first";
if ("undefined" === typeof commonMethod) throw "Dropdown requires commonMethod to be loaded first";
a(jQuery, monment,cm);
}
})(function($, moment, cm){}();
注:1、开头加分号含义是避免加载其他插件时,其他插件结尾未加分号;
2、第一个if分支是amd写法(即兼容require),第二个分支是module对象exports属性赋值,第三个是如果都不是上面两种的第三种写法,先要判断是否包含jQuery、moment和commonMethod三个文件,如果没有先加载则抛出错误,然后加载。
3、总体是一个立即执行函数,在最后一个大括号中定义插件内容
2、插件内容写法
$.fn.EcoTable = function(opt){
//定义需要的属性和方法
var $el = $(this);
...
//定义所需要的插件方法,以fn开头
this.init();
}
var fn = $.fn.protype;
fn.init = function(){
//定义插件初始化需要完成的事情
...
this.attach();
}
fn.attach() = function(){
this.$el.on('click', '.click-class', function(){
//定义绑定事件
});
......
}
示例:
var EcoTable = function (el, opt) {
this.$el = $(el);
this.defaults = {
'type': opt.type,
'curParams': opt.curParams,
'data': opt.data,
'lang': opt.lang
}
tableLocales = $.extend(true, {}, tableLocales, $.fn.EcoTable.tableLocale); // 多语言
this.options = $.extend({}, defaults, opt); // 默认选项
lang = opt.lang;
this.init();
}
var fn = EcoTable.prototype;
3、插件结尾写法
$.fn.EcoTable = function (options) {
return this.each(function () {
var $this = $(this);
data = $this.data('EcoTable');
if (!data) {
$this.data('EcoTable', new EcoTable(this, options));
}
});
};
$.fn.EcoTable.tableLocale = {};
return $.fn.EcoTable;
注:1、插件的返回必须是this,因为本文是jQuery插件教程,所以插件必须要支持链式写法,所以必须返回this本身
2、第一个return是因为有可能有多个插件
3、data是插件的数据属性,可以返回插件的选项