jQuery 如何写插件 - 第二步

本文介绍jQuery插件开发的最佳实践,包括函数暴露、私有函数维护、Metadata支持及整合技巧等,帮助开发者创建强大且规范的插件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.4 适当的暴露一些函数

这段将会一步一步对前面那段代码通过有意思的方法扩展你的插件(同时让其他人扩展你的插件)。例如,我们插件的实现里面可以定义一个名叫"format"的函数来格式化高亮文本。我们的插件现在看起来像这样,默认的format方法的实现部分在hiligth函数下面。

// plugin definition  
$.fn.hilight = function(options) {  
  // iterate and reformat each matched element  
  return this.each(function() {  
    var $this = $(this);  
    // ...  
    var markup = $this.html();  
    // call our format function  
    markup = $.fn.hilight.format(markup);  
    $this.html(markup);  
  });  
};  
// define our format function  
$.fn.hilight.format = function(txt) {  
return '<strong>' + txt + '</strong>';  
};   

      我们很容易的支持options对象中的其他的属性通过允许一个回调函数来覆盖默认的设置。这是另外一个出色的方法来修改你的插件。这里展示的技巧是进一步有效的暴露format函数进而让他能被重新定义。通过这技巧,是其他人能够传递他们自己设置来覆盖你的插件,换句话说,这样其他人也能够为你的插件写插件。
      考虑到这个篇文章中我们建立的无用的插件,你也许想知道究竟什么时候这些会有用。一个真实的例子是Cycle插件.这个Cycle插件是一个滑动显示插件,他能支持许多内部变换作用到滚动,滑动,渐变消失等。但是实际上,没有办法定义也许会应用到滑动变化上每种类型的效果。那是这种扩展性有用的地方。 Cycle插件对使用者暴露"transitions"对象,使他们添加自己变换定义。插件中定义就像这样:
$.fn.cycle.transitions = {
// ...
};

这个技巧使其他人能定义和传递变换设置到Cycle插件。
2.5 保持私有函数的私有性
这种技巧暴露你插件一部分来被覆盖是非常强大的。但是你需要仔细思考你实现中暴露的部分。一但被暴露,你需要在头脑中保持任何对于参数或者语义的改动也许会破坏向后的兼容性。一个通理是,如果你不能肯定是否暴露特定的函数,那么你也许不需要那样做。
那么我们怎么定义更多的函数而不搅乱命名空间也不暴露实现呢?这就是闭包的功能。为了演示,我们将会添加另外一个“debug”函数到我们的插件中。这个 debug函数将为输出被选中的元素格式到firebug控制台。为了创建一个闭包,我们将包装整个插件定义在一个函数中。
 (function($) {  
  // plugin definition  
  $.fn.hilight = function(options) {  
    debug(this);  
    // ...  
  };  
  // private function for debugging  
  function debug($obj) {  
    if (window.console && window.console.log)  
      window.console.log('hilight selection count: ' + $obj.size());  
  };  
//  ...  
})(jQuery);   

我们的“debug”方法不能从外部闭包进入,因此对于我们的实现是私有的。

2.6 支持Metadata插件( 坦白说这个地方我不是很清楚...... )

在你正在写的插件的基础上,添加对Metadata插件的支持能使他更强大。个人来说,我喜欢这个Metadata插件,因为它让你使用不多的"markup”覆盖插件的选项(这非常有用当创建例子时)。而且支持它非常简单。更新:注释中有一点优化建议。
$.fn.hilight = function(options) {  
  // ...  
  // build main options before element iteration  
  var opts = $.extend({}, $.fn.hilight.defaults, options);  
  return this.each(function() {  
    var $this = $(this);  
    // build element specific options  
    var o = $.meta ? $.extend({}, opts, $this.data()) : opts;  
    //...    

 这些变动行做了一些事情:它是测试Metadata插件是否被安装如果它被安装了,它能扩展我们的options对象通过抽取元数据这行作为最后一个参数添加到JQuery.extend,那么它将会覆盖任何其它选项设置。现在我们能从"markup”处驱动行为,如果我们选择了“markup”:

 调用的时候可以这样写: jQuery.foo(); 或 $.foo();

<!--  markup  -->  
<div class="hilight { background: 'red', foreground: 'white' }">  
  Have a nice day!  
</div>  
<div class="hilight { foreground: 'orange' }">  
  Have a nice day!  
</div>  
<div class="hilight { background: 'green' }">  
  Have a nice day!  
</div>  
现在我们能高亮哪些div仅使用一行脚本:
$('.hilight').hilight();   
2.7 整合
下面使我们的例子完成后的代码:
// 创建一个闭包  
(function($) {  
  // 插件的定义  
  $.fn.hilight = function(options) {  
    debug(this);  
    // build main options before element iteration  
    var opts = $.extend({}, $.fn.hilight.defaults, options);  
    // iterate and reformat each matched element  
    return this.each(function() {  
      $this = $(this);  
      // build element specific options  
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;  
      // update element styles  
      $this.css({  
        backgroundColor: o.background,  
        color: o.foreground  
      });  
      var markup = $this.html();  
      // call our format function  
      markup = $.fn.hilight.format(markup);  
      $this.html(markup);  
    });  
  };  
  // 私有函数:debugging  
  function debug($obj) {  
    if (window.console && window.console.log)  
      window.console.log('hilight selection count: ' + $obj.size());  
  };  
  // 定义暴露format函数  
  $.fn.hilight.format = function(txt) {  
    return '<strong>' + txt + '</strong>';  
  };  
  // 插件的defaults  
  $.fn.hilight.defaults = {  
    foreground: 'red',  
    background: 'yellow'  
  };  
// 闭包结束  
})(jQuery);   

 这段设计已经让我创建了强大符合规范的插件。
3、总结
jQuery为开发插件提拱了两个方法,分别是:
jQuery.fn.extend(object);  给jQuery对象添加方法。
jQuery.extend(object);  为扩展jQuery类本身.为类添加新的方法。
3.1 jQuery.fn.extend(object);
fn 是什么东西呢。查看jQuery代码,就不难发现。
jQuery.fn = jQuery.prototype = { 
init: function( selector, context ) {//.... 
//...... 
};  

原来 jQuery.fn = jQuery.prototype.对prototype肯定不会陌生啦。虽然 javascript 没有明确的类的概念,但是用类来理解它,会更方便。jQuery便是一个封装得非常好的类,比如我们用 语句 $("#btn1") 会生成一个 jQuery类的实例。
jQuery.fn.extend(object); 对jQuery.prototype进得扩展,就是为jQuery类添加“成员函数”。jQuery类的实例可以使用这个“成员函数”。
比如我们要开发一个插件,做一个特殊的编辑框,当它被点击时,便alert 当前编辑框里的内容。可以这么做:
$.fn.extend({
     alertWhileClick:function(){ 
        $(this).click(function(){      
           alert($(this).val());  
         });   
      }      
});  
$("#input1").alertWhileClick(); //页面上为:<input id="input1" type="text"/>
$("#input1") 为一个jQuery实例,当它调用成员方法 alertWhileClick后,便实现了扩展,每次被点击时它会先弹出目前编辑里的内容。
3.2 jQuery.extend(object); 
为jQuery类添加添加类方法,可以理解为添加静态方法。如:
$.extend({ 
    add:function(a,b){return a+b;} 
});
便为 jQuery 添加一个为 add 的 “静态方法”,之后便可以在引入 jQuery 的地方,使用这个方法了,$.add(3,4); //return 7

当然如何做的更好,可去官方网站:
http://docs.jquery.com/Plugins/Authoring
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值