编写jQuery插件

一般编写插件是给jQuery.fn添加一个新的函数属性:

jQuery.fn.myPlugin = function(){
    ……
}

但是为了使用我们熟悉的 使IIFEjQuery使 :

(function(){
    $.fn.myPlugin = function(){
        ……
    }
})(jQuery);

此时在插件内部的this就是指向调用此方法的jQuery对象。

为了保证jQuery的链式调用,我们需要在插件最后返回this:

(function($){
    $.fn.myPlugin = function(){
        ……
        return this;
    }
})(jQuery);

由于jQuery插件都可以批量对选择器选取的对象进行操作,因此在插件中需要对每一个都进行处理:

(function($){
    $.fn.myPlugin = function(){
        return this.each(function(){ …… });
    }
})(jQuery);

一般插件会设置一些默认选项,我们有时要利用用户传入的参数来更改配置,这时就要使用到$.extend().

(function(){
    $.fn.myPlugin = function(options){
        $.extend({ base:100, color:'black' },options)
        ……
        return this.each(function(){ …… });
    }
})(jQuery);
$("div").myPlugin({color:'red'});

想要为插件定义不同的方法,永远不要在 jQuery.fn 对象中声明一个以上的名称空间:

(function( $ ){

  $.fn.tooltip = function( options ) { 
    // 这
  };
  $.fn.tooltipShow = function( ) {
    // 不
  };
  $.fn.tooltipHide = function( ) { 
    // 好
  };
  $.fn.tooltipUpdate = function( content ) { 
    // !!!  
  };

})( jQuery );

应该把所有的插件方法收集到一个对象定义中,并通过传递方法名称字符串调用:

(function($){
    $.fn.myPlugin = function(method){
        if(methods[method]){
            return methods[method].apply(this,[].slice.call(arguments,1));
        }else if(typeof method === 'object' || !method){
            return methods.init.apply(this,arguments);
        }else{
            $.error();
        }
    }

    var methods = {
        init:function(options){……},
        show:functoin(){},
        hide:function(){},
        update:function(){}
    }
})(jQuery);
$("div").myPlugin();  //调用init方法
$("div").myPlugin({   //调用init方法
    foo:bar;
});

$("div").myPlugin("hide")  //调用hide方法
$('div').myPlugin('update', 'This is the new tooltip content!');  // 调用 update 方法

这种插件架构使你可以在插件的父闭包中封装所有方法,调用时先传方法名称字符串,接下来再把你需要的其它参数传给该方法。

这种封装和架构是 jQuery 插件社区的一个标准,已经被无数插件所使用,包括 jQueryUI 中的插件和小部件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值