当前位置: 代码迷 >> 综合 >> jQuery.proxy()代理、回调方法
  详细解决方案

jQuery.proxy()代理、回调方法

热度:28   发布时间:2024-01-18 12:08:05.0

jQuery.proxy(),接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文(context )语境。

·         jQuery.proxy( function, context )

function将要改变上下文语境的函数。

context函数的上下文语境(`this`)会被设置成这个 object 对象。

·         jQuery.proxy( context, name )

context函数的上下文语境会被设置成这个 object 对象。

name将要改变上下文语境的函数名(这个函数必须是前一个参数 ‘context’ 对象的属性)

这个方法通常在向一个元素上附加事件处理函数时,上下文语境实际是指向另一个对象的情况下使用。

另外,jQuery 能够确保即使你绑定的函数是经过 jQuery.proxy() 处理过的函数,你依然可以用原先的函数来正确地取消绑定。

看一下官方的例子:

01

var obj = {

02

name: "John",

 

03

test: function() {

04

alert( this.name );

 

05

$("#test").unbind("click", obj.test);

06

}

 

07

};

08

 

 

09

$("#test").click( jQuery.proxy( obj, "test" ) );

10

 

 

11

// 以下代码跟上面那句是等价的:

12

// $("#test").click( jQuery.proxy( obj.test, obj ) );

 

13

 

14

// 可以与单独执行下面这句做个比较。

 

15

// $("#test").click( obj.test );

再看一下jquery.proxy的源码:

01

 

04

jQuery.proxy = function( fn, proxy, thisObject ) {

 

05

    if ( arguments.length === 2 ) {

06

        // jQuery.proxy(context, name);

 

07

        if ( typeof proxy === "string" ) {

08

            thisObject = fn;

 

09

            fn = thisObject[ proxy ];

10

            proxy = undefined;

 

11

 

12

            

 

17

        }

18

        // jQuery.proxy(name, context);

 

19

        else if ( proxy && !jQuery.isFunction( proxy ) ) {

20

            thisObject = proxy;

 

21

            proxy = undefined;

22

        }

 

23

    }

24

    if ( !proxy && fn ) {

 

25

        

26

        proxy = function() {

 

27

            return fn.apply( thisObject || this, arguments );

28

        };

 

29

    }

30

    // Set the guid of unique handler to the same of original handler, so it can be removed

 

31

    if ( fn ) {

32

        proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;

 

33

    }

34

    // So proxy can be declared as an argument

 

35

    return proxy;

36

}

其实就是平常使用的的call和apply,大部分的时候作为回调使用。

  相关解决方案