jQuery中$.proxy()的原理和使用

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   strong   

jQuery.proxy(),接受一個函數,然後返回一個新函數,並且這個新函數始終保持了特定的上下文(context )語境。

  • jQuery.proxy( function, context )

    function將要改變上下文語境的函數。

    context函數的上下文語境(`this`)會被設定成這個 object 對象。

  • jQuery.proxy( context, name )

    context函數的上下文語境會被設定成這個 object 對象。

    name將要改變上下文語境的函數名(這個函數必須是前一個參數 ‘context’ 對象的屬性)

這個方法通常在向一個元素上附加事件處理函數時,上下文語境實際是指向另一個對象的情況下使用。

另外,jQuery 能夠確保即使你綁定的函數是經過 jQuery.proxy() 處理過的函數,你依然可以用原先的函數來正確地取消綁定。

看一下官方的例子:

var obj = {name: "John",test: function() {alert( this.name );$("#test").unbind("click", obj.test);}};$("#test").click( jQuery.proxy( obj, "test" ) );// 以下代碼跟上面那句是等價的:// $("#test").click( jQuery.proxy( obj.test, obj ) );// 可以與單獨執行下面這句做個比較。// $("#test").click( obj.test );

可以看一下jQuery中的實現(1.6之前的版本):

/* jQuery 源碼之 proxy: 使用 apply 形式, 執行回呼函數.*/jQuery.proxy = function( fn, proxy, thisObject ) {    if ( arguments.length === 2 ) {        // jQuery.proxy(context, name);        if ( typeof proxy === "string" ) {            thisObject = fn;            fn = thisObject[ proxy ];            proxy = undefined;            /* 轉化結果:                thisObject -> context                fn -> name                proxy -> undefined             */        }        // jQuery.proxy(name, context);        else if ( proxy && !jQuery.isFunction( proxy ) ) {            thisObject = proxy;            proxy = undefined;        }    }    if ( !proxy && fn ) {        /* 使用 proxy 保證 函數執行時, context 為指定值 */        proxy = function() {            return fn.apply( thisObject || this, arguments );        };    }    // Set the guid of unique handler to the same of original handler, so it can be removed    if ( fn ) {        proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;    }    // So proxy can be declared as an argument    return proxy;}

其實就是平常使用的的call和apply,大部分的時候作為回調使用。

在stackoverflow上有個問題,其中的例子比較典型,供參考:

比如有如下代碼:

$(‘#myElement‘).click(function() {        // In this function, "this" is our DOM element.    $(this).addClass(‘aNewClass‘);});

這裡的this就是我們的DOM元素。如果我們要在增加class樣式之前需要等待一段時間,可能會將代碼寫成下面這樣(注意:有問題的代碼):

$(‘#myElement‘).click(function() {    setTimeout(function() {          // Problem! In this function "this" is not our element!        $(this).addClass(‘aNewClass‘);    }, 1000);});

這裡的this就不是我們期望的那個DOM元素了。解決方案就是使用jQuery的$.proxy()了,代碼如下:

$(‘#myElement‘).click(function() {   // ------------------v--------give $.proxy our function,    setTimeout($.proxy(function() {        $(this).addClass(‘aNewClass‘);  // Now "this" is again our element    }, this), 1000);   // ---^--------------and tell it that we want our DOM element to be the   //                      value of "this" in the function});

我們可以這樣來理解上面的代碼:

function() {    // v--------func is the function we gave to $.proxy    func.apply( ctx );    // ----------^------ ctx is the value we wanted for "this" (our DOM element)}

這就體現出來jQuery中$.proxy()的強大功效了。

注意:在jQuery 1.6及之後的版本中,除了上面提到的兩種用法之外,proxy還增加了其他兩種用法:

jQuery.proxy( function, context [, additionalArguments ] )
jQuery.proxy( context, name [, additionalArguments ] )

具體使用可以參考jQuery手冊。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.