DIV CSS 佈局教程網

jQuery 插件開發完全指南:類級與對象級兩大流派
編輯:JQuery特效代碼     

用 jQuery 寫久了自己動手做插件,幾乎是每個前端開發者的必經之路。jQuery 把插件的擴展方式歸納成兩條清晰的技術路線:一條是類級別(靜態方法),直接掛在 jQuery 這個「類」身上;另一條是對象級別(實例方法),掛在 jQuery.fn 也就是原型上,讓每一個選中的元素集合都能調用。下面把這兩條路線的常見寫法、設計要點與封裝技巧逐一拆解。

一、類級別插件:給 jQuery 添加全局函數

類級別插件最典型的代表就是 $.ajax()——它不針對任何 DOM 元素,只是一個掛在 jQuery 命名空間下的工具函數。共有四種常見擴展形式。

1. 新增單個全局函數

jQuery.foo = function() {
    alert('This is a test. This is only a test.');
};

2. 一次新增多個全局函數

jQuery.foo = function() {
    alert('This is a test. This is only a test.');
};
jQuery.bar = function(param) {
    alert('This function takes a parameter, which is "' + param + '".');
};

調用時與普通函數無異:jQuery.foo();、jQuery.bar('baz');,也可以簡寫成 $.foo();、$.bar('baz');。

3. 用 jQuery.extend() 批量掛載

寫法更乾淨,也更利於日後維護:

jQuery.extend({
    foo: function() {
        alert('This is a test. This is only a test.');
    },
    bar: function(param) {
        alert('This function takes a parameter, which is "' + param + '".');
    }
});

4. 使用自定義命名空間

即便 jQuery 本身已經佔用了大量名稱,插件之間撞名依然防不勝防。實踐中的通用做法是把相關方法收攏進一個獨立命名空間:

jQuery.myPlugin = {
    foo: function() {
        alert('This is a test. This is only a test.');
    },
    bar: function(param) {
        alert('This function takes a parameter, which is "' + param + '".');
    }
};

調用形式變為 $.myPlugin.foo(); 與 $.myPlugin.bar('baz');。這一招看起來樸素,卻能有效杜絕全局污染。

二、對象級別插件:給 jQuery 實例添加方法

對象級插件才是日常最常用的形態。基本骨架有兩種等價寫法:

(function($) {
    $.fn.extend({
        pluginName: function(opt, callback) {
            // 插件實現邏輯
        }
    });
})(jQuery);
(function($) {
    $.fn.pluginName = function() {
        // 插件實現邏輯
    };
})(jQuery);

把 jQuery 以實參形式傳入立即執行函數,好處是函數體內部可以放心使用 $ 這個別名,不必擔心與 Prototype 等庫的 $ 衝突。這是行業內公認的標準寫法,請養成習慣。

1. 在命名空間下只申明一個名字

一個插件最好只暴露一個入口。若你的插件包含成對的功能(例如 doSomething() 與 undoSomething()),可以通過把輔助函數掛成該函數的屬性來避免污染命名空間——畢竟在 JavaScript 裡函數也是對象。

$.fn.hilight = function() {
    // 插件實現邏輯
};
// 調用: $('#myDiv').hilight();

2. 用 options 參數控制插件行為

$.fn.hilight = function(options) {
    var defaults = {
        foreground: 'red',
        background: 'yellow'
    };
    var opts = $.extend(defaults, options);
    // 插件實現邏輯
};
// 調用
$('#myDiv').hilight({ foreground: 'blue' });

3. 把默認配置暴露出去

更進一步的做法,是把默認值掛成插件函數的屬性,讓使用者能一行代碼改全局默認:

$.fn.hilight = function(options) {
    // 第一個參數傳空對象,避免污染 defaults
    var opts = $.extend({}, $.fn.hilight.defaults, options);
    // 插件實現邏輯
};
$.fn.hilight.defaults = {
    foreground: 'red',
    background: 'yellow'
};

使用者於是既可以一次性改默認值:

$.fn.hilight.defaults.foreground = 'blue';
$('.hilightDiv').hilight();

也可以在調用時臨時覆蓋:

$('#green').hilight({ foreground: 'green' });

4. 適度暴露內部函數

把關鍵的處理函數(例如格式化文本的 format)也掛到插件對象上,等於把擴展點交給了社群——別人就能「為你的插件寫插件」。

$.fn.hilight = function(options) {
    return this.each(function() {
        var $this = $(this);
        var markup = $this.html();
        markup = $.fn.hilight.format(markup);
        $this.html(markup);
    });
};
$.fn.hilight.format = function(txt) {
    return '<strong>' + txt + '</strong>';
};

真實案例是傳說中的 Cycle 插件:它把 transitions 對象公開出來,使用者便能自行定義滾動、滑動、淡出等各種轉場效果。

5. 用閉包保護私有函數

暴露是強大的,但一旦暴露就背上了向後兼容的包袱。拿不準要不要公開的函數,乾脆別公開。閉包正是那把保護傘:

(function($) {
    $.fn.hilight = function(options) {
        debug(this);
        // ...
    };
    // 私有調試函數,外部無法訪問
    function debug($obj) {
        if (window.console && window.console.log) {
            window.console.log('hilight selection count: ' + $obj.size());
        }
    }
})(jQuery);

6. 兼容 Metadata 插件

支持 Metadata 插件後,配置就能直接寫在 HTML 標記裡,做示例頁面時格外省事:

$.fn.hilight = function(options) {
    var opts = $.extend({}, $.fn.hilight.defaults, options);
    return this.each(function() {
        var $this = $(this);
        var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
        // ...
    });
};

標記端寫成:

<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>

一行腳本搞定全部:$('.hilight').hilight();

7. 整合後的完整形態

(function($) {
    $.fn.hilight = function(options) {
        debug(this);
        var opts = $.extend({}, $.fn.hilight.defaults, options);
        return this.each(function() {
            var $this = $(this);
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            $this.css({
                backgroundColor: o.background,
                color: o.foreground
            });
            var markup = $this.html();
            markup = $.fn.hilight.format(markup);
            $this.html(markup);
        });
    };
    function debug($obj) {
        if (window.console && window.console.log) {
            window.console.log('hilight selection count: ' + $obj.size());
        }
    }
    $.fn.hilight.format = function(txt) {
        return '<strong>' + txt + '</strong>';
    };
    $.fn.hilight.defaults = {
        foreground: 'red',
        background: 'yellow'
    };
})(jQuery);

閉包 + 默認值 + 可覆蓋的擴展點 + 私有工具函數,這套組合拳足以支撐起規範、耐用且易於協作的前端插件。

三、總結:兩個 extend 的分工

一句話記住區別:jQuery.extend(object) 擴展的是類本身,添加靜態方法;jQuery.fn.extend(object) 擴展的是原型,添加實例方法。

而 fn 到底是什麼?翻開源碼便一目了然:

jQuery.fn = jQuery.prototype = {
    init: function(selector, context) { /* ... */ }
};

雖然 JavaScript 沒有嚴格意義上的類,但用類的心智模型去理解會輕鬆很多。當我們寫下 $("#btn1") 時,得到的就是一個 jQuery 實例;jQuery.fn.extend() 往原型上加的成員函數,這個實例自然就能調用。

舉個實際例子——做一個被點擊就彈出自身內容的輸入框:

$.fn.extend({
    alertWhileClick: function() {
        $(this).click(function() {
            alert($(this).val());
        });
    }
});
$("#input1").alertWhileClick();

而靜態方法則這樣添加:

$.extend({
    add: function(a, b) { return a + b; }
});
$.add(3, 4); // 返回 7
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved