JS(二十六)jQuery插件编写技巧

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是插件的数据属性,可以返回插件的选项

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fullstack_lth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值