• jquery.proxy的四种使用场景及疑问


    作者:zccst

    其实只有两种使用方式,只不过每一种又细分是否传参。

    先给一段HTML,后面会用来测试:

    <p><button id="test">Test</button></p>
    <p id="log"></p>

    1,jQuery.proxy(function, context);

    使用context作为function运行上下文(即this)

    2,jQuery.proxy(function, context [, additionalArguments]);

    传递参数给function

    使用场景:click时,执行function,在给定的context里,同时传递两个参数,如果需要event,则可以作为function第三个参数。

    注意:function执行的环境如果不适用proxy,则context会是当前点击对象,现在指定了其他的上下文,已经跟当前点击对象没有一点关系了。

     1 var me = {
     2   /* I'm a dog */
     3   type: "dog",
     4  
     5   /* Note that event comes *after* one and two */
     6   test: function(one, two, event) {
     7     $("#log")
     8       /* `one` 是第一个附加参数,与对象`you`对应 */
     9       .append( "<h3>Hello " + one.type + ":</h3>" )
    10       /* `two` 是第二个附加参数,与对象`they`对应 */
    11       .append( "and they are " + two.type + ".<br>" )
    12       /* `this` 是上下文,与普通对象`me`对应 */
    13       .append( "I am a " + this.type + ", " )
    14  
    15       
    16       /* 事件类型是点击"click" */
    17       .append( "Thanks for " + event.type + "ing " )
    18       /* `event.target`是被点击元素,类型是按钮button */
    19       .append( "the " + event.target.type + "." );
    20   }
    21 };
    22  
    23 var you  = { type: "cat" };
    24 var they = { type: "fish" };
    25  
    26 
    27 /* 一共4个参数:第一个是function,第二个是context,第三、四是参数 */
    28 var proxy = $.proxy( me.test, me, you, they );
    29 
    30 $("#test").on( "click", proxy );
    31 /* 运行结果:
    32 Hello cat:
    33 and they are fish.
    34 I am a dog, Thanks for clicking the submit.
    35 */

     在这种情况下,click仅仅相当于一个触发按钮,触发后执行的函数,跟click一点关系都没有了。

    3,jQuery.proxy(context, name);

    使用场景:context是一个PlainObject,name是其方法。在click时执行,但test函数执行的上下文是obj,不是$("#test")

    1 var obj = {
    2     name: "John",
    3     test: function() {
    4         console.log(this);
    5         $("#log").append( this.name );
    6         $("#test").off("click", obj.test);
    7     }
    8 };
    9 $("#test").on( "click", jQuery.proxy( obj, "test" ) );//在click时执行,但又不是click的上下文

    结果分析:在绑定点击事件后,第一次执行时,就把该绑定去除了。

    去除之后,button上已经没有点击事件,所以再点击按钮,也不会有任何反应了。 

    4,jQuery.proxy(context, name [, additionalArguments]);

    一个疑问:

    请教大家一个问题,
    jQuery.proxy(context, function, params);

    function.call(context,params);
    区别是什么?
    我遇到一个问题是用proxy没反应,用call时就有反应。

  • 相关阅读:
    OSI Model Reference graphic / What do you guys think? Anything to edit/remove/add?
    Iframe Target for a Link
    Abp FullAuditedAggregateRoot
    After Effects上课视频
    Openwrt NAT ALG
    ipcalc.sh
    网络流量测试工具
    NatTypeTester
    基于DPDK开源项目
    GPS的调试与报文解析
  • 原文地址:https://www.cnblogs.com/zccst/p/3768537.html
Copyright © 2020-2023  润新知