一步一步教你写一个jQuery的插件教程(Plugin) |
本文标签:jQuery,插件教程 jQuery 的plugin开发需要注意的事情, 1. 明确jQuery的命名空间只有一个 在我们的例子里,我们将会命名这个插件名字为hilight, 也就是我们的plugin可以通过下面的方法来使用: 为什么jQuery的plugin只有一个命名空间?可能是设计的要求,或者是这样的话可读性更强,亦或是为了面向对象的设计模式 。 2.明白options参数来控制plugin的行为 。 让我们先为我们的hilight插件明确一下foreground和background的颜色 。我们应该能够允许这两个option作为option对象传递给plugin的主函数 。例如: 现在插件能够设定如下的属性: 3. 为默认的plugin设定提供公共的访问权限 。 我们这里可以改进一下,就是让上面的代码能够设置能够扩展 。这样当使用这个插件的用户能够使用最少的代码重载我们的option 。这也就是我们开始使用function对象的好处 。 现在用户可以在他们的script中使用一行代码来设置foreground属性: 有了上面的代码我们就可以把某个DOM控件的foregrounf颜色设定为blue了 。 4. 为子函数提供公共的访问权限 这个条款和上面的相仿,能很有趣的让你的Plugin有扩展功能 。例如:在lilight的plugin中我们能够定义一个function是format,可以定义hilight的text的形式 。我们的plugin代码将会显示如下: 这里我们可以很容易支持另外的一个option对象来通过一个callback 函数来重载默认的formatting 。那将会是另外一个不错的支持自定义的方式 。 5. 私有的函数绝对是私有访问 公开plugin的一些Option能够被自定义当然是个非常强大的功能 。但是你需要考虑哪部分应该被公开,哪部分不应该通过外部访问,否则会破会你已经封装好的结果 。 这里debug方法不能从外部访问,因为他在plugin的展现中属于私有的方法 。 6.支持metadata plugin 。 使用Metadata Plugin需要看你的plugin是什么类型,可能它会使你的插件功能更加强大 。个人来说,我比较喜欢metadata plugin是因为它能偶让我的plguin的option通过标记重载 。 如果metadata plugin能够成功的封装到我们的插件,那么可以通过下面的标记来使用这个lilight插件 。 最终代码如下: 复制代码 代码如下: // // create closure // (function($) { // // plugin definition // $.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); }); }; // // private function for debugging // function debug($obj) { if (window.console && window.console.log) window.console.log(hilight selection count: + $obj.size()); }; // // define and expose our format function // $.fn.hilight.format = function(txt) { return <strong> + txt + </strong>; }; // // plugin defaults // $.fn.hilight.defaults = { foreground: red, background: yellow }; // // end of closure // })(jQuery); |