编写jQuery插件

来源:互联网 发布:ledv3.zh3软件下载 编辑:程序博客网 时间:2024/06/03 23:59

一般编写插件是给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 中的插件和小部件。

原创粉丝点击