$.fn.hight = function(options){
//iterate and reformat each mached 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>';
};
保持私有函数
暴露插件有部分内容提供重写看上去似乎非常强大,但是你必须认真地考虑你的插件哪一部分是需要暴露出来的。一旦暴露出来,你就需要考虑这些变化点,一般情况下,如果你没有把握哪部分需要暴露出来,那么你可以不这样做。
那如何才能够定义更多的函数而不将其暴露出来呢?这个任务就交给闭包吧。为了证实,我们在插件中添加一个函数叫“debug”,这debug函数将会记录已选择的元素数量到FireBug控制台中。为了创建闭包,我们将插件定义的整部分都包装起来:
//create closure
(function($){
//plugin definition
$.fn.hilight = function(options){
debug(this);
//...
};
//private function for debuggin
function debug($obj){
if(window.console && window.console.log){
window.console.log('hilight selection count :' + $obj.size());
}
}
//...
//end of closure
})(jQuery);
这样“debug”方法就不能被闭包这外调用了
支持元数据插件
依赖于所写的插件类型,并支持元数据插件会使得其本身更加强大。个人来讲,我喜欢元素据插件,因为它能让你分离标签中重写插件的配置(这在写demo和示例时特别有用)。最重要的是,想现实它特别的容易!
$.fn.hilight = function(options){
//build main options before element interation
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;
//一般句话,搞定支持元数据 功能
});
}
几行的变化完成了以下几件事:
1、检测元数据是否已经配置
2、如果已配置,将配置属性与额外的元数据进行扩展
<!-- 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();
最后,将全部代码放在一起:
//
//create closure
//
(function($){










