原文:http://www.itzhai.com/jquery-plug-in-the-preparation-of-related-technical-design-summary-and-best-practices.html
1、声明插件名称:

添加一个函数到jQuery.fn(jQuery.prototype)对象,该函数的名称就是你的插件名称:

jQuery.fn.myPlugin = function() {

  // Do your awesome plugin stuff here

};

在命名不与jQuery其他函数冲突的情况,可以使用闭包的方式使用$符号:

(function( $ ) {
$.fn.myPlugin = function() { // Do your awesome plugin stuff here };
})( jQuery );
2、插件中的上下文:

jQuery接收一个回调,该回调本身就指向了dom,直接使用this就相当于我们平时的$(this)的情况:

(function( $ ){

  $.fn.myPlugin = function() {

    // there's no need to do $(this) because
// "this" is already a jquery object // $(this) would be the same as $($('#element')); this.fadeIn('normal', function(){ // the this keyword is a DOM element }); };
})( jQuery );
$('#element').myPlugin();

下面是一个简单的jQuery插件,实现获取所有div的最大高度:

(function( $ ){

  $.fn.maxHeight = function() {

    var max = 0;

    this.each(function() {
max = Math.max( max, $(this).height() );
}); return max;
};
})( jQuery );
var tallest = $('div').maxHeight(); // Returns the height of the tallest div
3、维护链接性:

前面的示例返回一个整数值最高的div,但是通常的意图仅在某种程度上是仅修改插件的元素集合,并将它们传递到下一个链中的方法。这样的jQuery的设计优雅的地方。所以保持链接性放到一个插件,您必须确保您的插件返回这个关键字。

(function( $ ){

  $.fn.lockDimensions = function( type ) {  

    return this.each(function() {

      var $this = $(this);

      if ( !type || type == 'width' ) {
$this.width( $this.width() );
} if ( !type || type == 'height' ) {
$this.height( $this.height() );
} }); };
})( jQuery );
$('div').lockDimensions('width').css('color', 'red');

因为插件返回this关键字的范围,它维护链接性,jQuery可以继续利用jQuery方法,如. css。所以,如果你的插件不返回一个内在价值,你应该总是返回this。

4、参数的传递,Defaults和Options:
(function( $ ){

  $.fn.tooltip = function( options ) {  

    // Create some defaults, extending them with any options that were provided
var settings = $.extend( {
'location' : 'top',
'background-color' : 'blue'
}, options); return this.each(function() { // Tooltip plugin code here }); };
})( jQuery );
$('div').tooltip({
'location' : 'left'
});

通过$.extend合并默认参数和调用者传入的参数。

5、命名空间:

正确的命名空间在插件开发中是一个非常重要的部分。正确的命名空间,可以确保你的插件将有一个很低的几率在同一个页面上被他插件或代码覆盖。

在任何情况下都不应该在一个插件的jQuery.fn对象中声称多个名称空间。

(function( $ ){

  $.fn.tooltip = function( options ) {
// THIS
};
$.fn.tooltipShow = function( ) {
// IS
};
$.fn.tooltipHide = function( ) {
// BAD
};
$.fn.tooltipUpdate = function( content ) {
// !!!
}; })( jQuery );

你应该收集所有的方法到一个对象化字面,并且通过方法的字面值进行调用:

(function( $ ){

  var methods = {
init : function( options ) {
// THIS
},
show : function( ) {
// IS
},
hide : function( ) {
// GOOD
},
update : function( content ) {
// !!!
}
}; $.fn.tooltip = function( method ) { // Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
} }; })( jQuery ); // calls the init method
$('div').tooltip(); // calls the init method
$('div').tooltip({
foo : 'bar'
});
// calls the hide method
$('div').tooltip('hide');
// calls the update method
$('div').tooltip('update', 'This is the new tooltip content!');

这种类型的方法封装和体系结构在jQuery插件社区中是一个标准,它适用于无数的插件,包括jQueryUI插件和小部件。

6、Events:

Bind方法允许通过命名空间的方式绑定事件,如果你的插件绑定了事件,可以通过命名空间的方式,在解除绑定事件时,你也可以这样做,来防止影响到其他的事件。可以通过“.<namespace>” 的方式来设置绑定事件的命名空间。

(function( $ ){

  var methods = {
init : function( options ) { return this.each(function(){
$(window).bind('resize.tooltip', methods.reposition);
}); },
destroy : function( ) { return this.each(function(){
$(window).unbind('.tooltip');
}) },
reposition : function( ) {
// ...
},
show : function( ) {
// ...
},
hide : function( ) {
// ...
},
update : function( content ) {
// ...
}
}; $.fn.tooltip = function( method ) { if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
} }; })( jQuery );
$('#fun').tooltip();
// Some time later...
$('#fun').tooltip('destroy');
7、Data:

关于data方法可以参考官方的文档:http://docs.jquery.com/Data,既是在页面的元素中绑定存储数据。

这里通过编写插件,实现在页面中的每个元素都绑定一些当前的状态或者内容。

(function( $ ){

  var methods = {
init : function( options ) { return this.each(function(){ var $this = $(this),
data = $this.data('tooltip'),
tooltip = $('<div />', {
text : $this.attr('title')
}); // If the plugin hasn't been initialized yet
if ( ! data ) { /*
Do more setup stuff here
*/ $(this).data('tooltip', {
target : $this,
tooltip : tooltip
}); }
});
},
destroy : function( ) { return this.each(function(){ var $this = $(this),
data = $this.data('tooltip'); // Namespacing FTW
$(window).unbind('.tooltip');
data.tooltip.remove();
$this.removeData('tooltip'); }) },
reposition : function( ) { // ... },
show : function( ) { // ... },
hide : function( ) { // ... },
update : function( content ) { // ...}
}; $.fn.tooltip = function( method ) { if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
} }; })( jQuery );
关于jQuery设计的总结和最佳实践:

编写jQuery插件允许您实现最大的类库,抽象出你认为有用的功能和可重用的代码,可以节省你的时间,使你的开发更加有效。记住当开发您的下一个jQuery插件,可以遵循下面的一个简短的总结:

1、 总是把你的插件放入闭包中:

(function( $ ){ /* plugin goes here */ })( jQuery );

2、 在你的插件直接范围内,不要多余的包裹住this关键字;

3、 除非你是从你的插件中返回一个内在的值,一般都返回你的插件的函数this关键字来维护链接性;

4、 与其传入冗长的参数,不如通过你的插件设置一个默认的参数,通过$.extend()方法进行扩展参数;

5、 不要在一个插件中使用多个命名空间导致jQuery.fn对象变得很杂乱;

6、 总是为你的方法,事件和data创建命名空间。

关于具体的插件开发说明,参考jQuery的官方文档:

http://docs.jquery.com/Plugins/Authoring

jQuery插件的编写相关技术 设计总结和最佳实践的更多相关文章

  1. jQuery插件的编写和使用 <思维导图>

    以下是jQuery插件的编写和使用的思维导图,全屏观看,请点击:jQuery插件的编写和使用

  2. Jquery插件的编写和使用

    第七章 Jquery插件的编写和使用    插件的定义: 插件也称为扩展,是一种遵循一定规范的应用程序接口编写出来的程序. 下面是Jquery插件的编写很使用:要查看请点击:Jquery插件的编写很使 ...

  3. 使用jquery插件实现图片延迟加载技术(懒加载)

    有时我们看到一些大型网站,页面如果有很多图片的时候,当你滚动到相应的行时,当前行的图片才即时加载的,这样子的话页面在打开只加可视区域的图片,而其它隐藏的图片则不加载,一定程序上加快了页面加载的速度,对 ...

  4. jquery插件的编写

    今天尝试了一下自己编写插件.最简单的jquery效果,返回顶部的按钮. 增加多个全局函数 添加多个全局函数,可采用如下定义: Java代码 jQuery.foo = function() { aler ...

  5. jQuery插件——1.编写规则

    jQuery插件编写规则如下: 1.命名规则:jquery.[插件名称].js 2.所有对象方法都应当附加到jQuery.fn对象上:所有的全局方法都应当附加到jQuery对象上. 3.在插件内部,t ...

  6. jquery 插件的编写

    /** * 插件的学习 * 原文地址:http://www.cnblogs.com/Wayou/p/jquery_plugin_tutorial.html#home */ ;(function($, ...

  7. [转]15年双11手淘前端技术巡演 - H5性能最佳实践

    [原文地址]:https://github.com/amfe/article/issues/21 前言 2015年是全面『无线化』的一年,在BAT(财报)几家公司都已经超过50%的流量来自移动端,这次 ...

  8. jQuery插件编写及链式编程模型小结

    JQuery极大的提高了我们编写JavaScript的效率,让我们可以愉快的编写代码,做出各种特效.大多数情况下,我们都是使用别人开发的JQuery插件,今天我们就来看看如何把我们常用的功能做出JQu ...

  9. jQuery插件编写及链式编程模型

    jQuery插件编写及链式编程模型小结 JQuery极大的提高了我们编写JavaScript的效率,让我们可以愉快的编写代码,做出各种特效.大多数情况下,我们都是使用别人开发的JQuery插件,今天我 ...

随机推荐

  1. JS数据绑定模板artTemplate试用

    之前写JS绑定数据曾经用过tmpl库,虽然功能比较强大但是感觉不是很轻量,对于相对简单的数据需求显得有些臃肿.而Ajax返回数据自己拼接html的方式又显得不够高端,因此今天看了一篇介绍artTemp ...

  2. 有效的XML: DTD(文档类型定义)介绍(转)

    文档类型定义和命名空间 有效(Valid)的XML文档: 首先,XML文档是个格式正规的(Well-formed)XML文档:(见格式正规的XML:语法 属性 实体 处理指令 样式单 CDATA节). ...

  3. hdu 4915 Parenthese sequence 多校第五场

    推断一个序列是否是有效是简单的. 可是推断序列是不是有多个解会出问题. 那么从i=0 ~l 假设读到问号,推断该问号成为(能否有效,该问号为)是否有效. 假设都有效,则必有多个解. 假设都无效,则无解 ...

  4. asp.net学习之SqlDataSource

    原文:asp.net学习之SqlDataSource 通过 SqlDataSource 控件,可以使用 Web 服务器控件访问位于关系数据库中的数据.其中可以包括 Microsoft SQL Serv ...

  5. Oracle 多表关联更新

    drop table course; create table course ( id integer, teacherNo integer, teacherDesc ), teacherName ) ...

  6. android账号与同步之发起同步

    上一篇博文我介绍了账号与同步的同步实现过程,当中提供了一个工系统进程调用的服务,那么这个服务究竟是怎么被启动和使用的呢?这篇博文我就大体梳理一下启动过程. 事实上作为一个一般开发者,我们仅仅要知道要想 ...

  7. 使用Maven在Eclipse中创建Web项目[转]

    一.新建 Maven Web项目 1.新建Maven Project new project-->选择 Maven Project --> 下一步 选择工作空间 -->下一步 在Fi ...

  8. 2077 汉诺塔IV

    Problem Description 还记得汉诺塔III吗?他的规则是这样的:不允许直接从最左(右)边移到最右(左)边(每次移动一定是移到中间杆或从中间移出),也不允许大盘放到小盘的上面.xhd在想 ...

  9. linux后台server开发环境的部署配置和验证(nginx+apache+php-fpm+FASTCGI(C/C++))

    linux后台server开发环境部署配置 引言 背景 随着互联网业务的不断增多.开发环境变得越来越复杂,为了便于统一server端的开发部署环境,特制定本配置文档. 使用软件 CentOS 6.3( ...

  10. JBPM——MyEclipse开发环境的搭建

    第一次接触JBPM我不知道如何在工程中的应用.查了一些资料.大约在JBPM随着时代的发展有一定的了解.首先JBPM它是JBoss件平台的一个组成部分.是一个灵活的,易扩展的工作流管理系统,仅仅只是这个 ...