DIV CSS 佈局教程網

jQuery 插件封裝的十個要點與最佳實踐
編輯:JQuery入門技巧     

寫好一個 jQuery 插件,能把最常用的功能沉澱成可複用的代碼,節省大量重複勞動。本文系統梳理插件開發的關鍵環節,從入門骨架一路講到命名空間、事件、數據管理,最後給出清單式的最佳實踐。

一、入門:插件掛在哪裡

編寫 jQuery 插件,起點是給 jQuery.fn 添加新的屬性,屬性名就是插件名。

jQuery.fn.myPlugin = function () {
    // 你自己的插件代碼
};

那個大家都愛的 $ 符號去哪了?它還在,但為了避免與其他 JavaScript 庫( Prototype、MooTools 等)衝突,最佳做法是把 jQuery 傳入一個自執行閉包,在閉包內把 $ 映射為 jQuery。

(function ($) {
    $.fn.myPlugin = function () {
        // 你自己的插件代碼
    };
})(jQuery);

這樣在閉包內部可以放心無限地使用 $,不必擔心被別的庫覆寫。

二、環境:this 到底是什麼

在插件的主體作用域中,this 關鍵字代表即將被執行的 jQuery 對象。這裡最容易犯一個錯:在其他接受 callback 的 jQuery 方法裡,this 代表原生 DOM 元素,於是很多人下意識地把 this 再包一層 $(this)——在插件主體裡這是多餘的。

(function ($) {
    $.fn.myPlugin = function () {
        // 此處無需 $(this),因為 this 已經是 jQuery 對象
        // $(this) 等價於 $($('#element'))
        this.fadeIn('normal', function () {
            // 但在 callback 內部,this 代表一個 DOM 元素,這裡需要 $(this)
        });
    };
})(jQuery);

$('#element').myPlugin();

記住這條界線:插件頂層的 this 是 jQuery 對象,回調裡的 this 是 DOM 元素。

三、基礎:寫一個真正做事的插件

(function ($) {
    $.fn.maxHeight = function () {
        var max = 0;
        this.each(function () {
            max = Math.max(max, $(this).height());
        });
        return max;
    };
})(jQuery);

var tallest = $('div').maxHeight();   // 返回高度最大的 div 的高度

注意這裡用了 this.each()——回調中的 this 是 DOM 元素,所以必須用 $(this) 才能調 height()。

四、維護 chainability(鏈式調用)

很多時候插件只是以某種方式修改選中的元素,然後把它們傳給鏈中的下一個方法。這正是 jQuery 設計的精妙之處,也是它如此受歡迎的原因之一。要保持鏈式,插件必須返回 this。

(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,後續的 .css() 得以繼續鏈接。順帶一提,傳給插件的參數(這裡的 'width')會直接出現在插件作用域中作為函數參數。

五、默認值與選項

對於較複雜、可定制項多的插件,最好提供一份可被覆蓋的默認設置,並用 $.extend 完成合併。這樣調用時只需傳一個對象,寫你想改的那幾項即可。

(function ($) {
    $.fn.tooltip = function (options) {
        var settings = $.extend({
            'location': 'top',
            'background-color': 'blue'
        }, options);

        return this.each(function () {
            // Tooltip 插件代碼
        });
    };
})(jQuery);

$('div').tooltip({ 'location': 'left' });

此例中最終生效的設置為 { 'location': 'left', 'background-color': 'blue' }。這是一種非常靈活的模式:既提供了高度可配置的插件,又不要求使用者記住全部選項。

六、命名空間的重要性

正確的命名空間是插件開發中至關重要的一環。良好的命名空間能讓你的插件極大程度地避免被同頁面的其他插件或代碼覆蓋;同時也讓開發者更容易追蹤自己的方法、事件與數據。

七、插件方法的組織

任何情況下,一個插件都不應該在 jQuery.fn 上佔有多個命名空間:

// 反例:把.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) {
        // 方法調用
        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);

// 調用 init
$('div').tooltip();
$('div').tooltip({ foo: 'bar' });

// 調用 hide
$('div').tooltip('hide');

// 調用 update
$('div').tooltip('update', 'This is the new tooltip content!');

這種架構把所有方法封裝在父層,通過傳遞方法名與所需參數來調用。它是 jQuery 插件社區的事實標準,jQuery UI 中的大量插件與 widget 都採用此模式。

八、事件:記得加命名空間

一個鮮為人知但很實用的功能是:bind() 支持為事件加命名空間。若插件綁定了事件,養成加命名空間的習慣,這樣在解除綁定時不會誤傷其他已綁定的同類型事件。做法是拼接 .命名空間。

(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();
// 一段時間之後
$('#fun').tooltip('destroy');

此例中 tooltip 初始化時把 reposition 綁到 resize 並加上 .tooltip 命名空間;銷毀時傳遞 '.tooltip',就能安全地只解除自己的綁定,不影響插件之外的代碼。

九、數據:用 data 記錄狀態

插件開發中常需要標記「某元素是否已初始化」或保存內部狀態。jQuery.data() 是基於元素記錄變量的好途徑。與其散落保存多個不同名字的 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 (!data) {
                    // 其他初始化工作
                    $this.data('tooltip', {
                        target: $this,
                        tooltip: tooltip
                    });
                }
            });
        },
        destroy: function () {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data('tooltip');

                $(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);

把數據按命名空間封裝在一個對象裡,能讓所有插件屬性集中可讀,也便於在 destroy 時一次性清理。

十、總結與最佳實踐清單

編寫 jQuery 插件能把最有用的功能沉澱為可重用代碼,節省開發者的時間、提升效率。動手時請牢記:

1. 總是用閉包包裹插件:

(function ($) {
    /* 插件代碼寫在這裡 */
})(jQuery);

2. 不要在插件功能範圍內多餘地把 this 包進 $。
3. 除非插件要返回特定值,否則始終返回 this 以維持鏈式。
4. 傳遞一個可擴展的默認對象參數,而不是一大堆位置參數。
5. 不要在一個插件裡反覆佔用多個命名空間。
6. 始終為方法、事件、數據加上命名空間。

附:一個自寫的放大鏡插件

(function ($) {
    $.fn.Fdj = function () {
        $('#smallImg').on('mouseover', function () {
            $('#slider').show();
        });
        $('#smallImg').on('mouseout', function () {
            $('#slider').hide();
        });
        $('#smallImg').on('mousemove', function (e) {
            // 計算選取框位置,並限制在圖片範圍內
            var x = e.clientX - $('#slider').width() / 2;
            var y = e.clientY - $('#slider').height() / 2;

            if (x <= 0) { x = 0; }
            if (x > $('#smallImg').width() - $('#slider').width()) {
                x = $('#smallImg').width() - $('#slider').width();
            }
            if (y <= 0) { y = 0; }
            if (y > $('#smallImg').height() - $('#slider').height()) {
                y = $('#smallImg').height() - $('#slider').height();
            }

            $('#slider').css({ 'left': x, 'top': y });

            // 按比例映射到大圖的偏移
            var X = x / $('#smallImg').width() * 800;
            var Y = y / $('#smallImg').height() * 800;
            $('#img').css({ left: -X, top: -Y });
        });
    };
})(jQuery);

這個小插件示範了放大鏡的核心原理:小圖上的選取框位置按比例換算成大圖的負偏移量。若想更符合上面的最佳實踐,可以把它重構為 methods 對象形式,把元素選擇器改為 this 上下文內查找,並把 800 這個魔法數字提取為可配置參數。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved