返回值:FunctionjQuery.proxy(function, context)

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

这个方法通常在向一个元素上附加事件处理函数时,上下文语境实际是指向另一个对象的情况下使用。另外,jQuery 能够确保即使你绑定的函数是经过 jQuery.proxy() 处理过的函数,你依然可以用原先的函数来正确地取消绑定。

需要您注意的是,jQuery 的事件绑定子系统会为每个事件处理函数分配一个唯一的 id 用于对其进行跟踪,这样的话,当需要解除绑定特定的事件处理时,系统就知道该解除绑定哪个事件处理函数了。jQuery.proxy() 参数中的 function 会被事件子系统当成一个单独的函数,即使是当它用于绑定不同的上下文时。为了避免错误的解除绑定事件,可以在绑定或解除绑定时,使用一个唯一的事件命令空间(例如, "click.myproxy1"),这样比在解除绑定时仅指定被代理函数要好。

示例:

修改使用参数为"function, context"的jQuery.proxy()方法绑定的点击事件的上下文语境。并且在第一次点击事件执行后,解除原先的绑定。

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>


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


<script>


var me = {
  type: "zombie",
  test: function(event) {
    // Without proxy, `this` would refer to the event target
    // use event.target to reference that element.
    var element = event.target;
    $(element).css("background-color", "red");

    // With proxy, `this` refers to the me object encapsulating
    // this function.
    $("#log").append( "Hello " + this.type + "<br>" );
    $("#test").unbind("click", this.test);
  }
};

var you = {
  type: "person",
  test: function(event) {
    $("#log").append( this.type + " " );
  }
};

// execute you.test() in the context of the `you` object
// no matter where it is called
// i.e. the `this` keyword will refer to `you`
var youClick = $.proxy( you.test, you );


// attach click handlers to #test
$("#test")
  // this === "zombie"; handler unbound after first click
  .click( $.proxy( me.test, me ) )
  // this === "person"
  .click( youClick )
  // this === "zombie"
  .click( $.proxy( you.test, me ) )
  // this === "<button> element"
  .click( you.test );


</script>
</body>
</html>

演示:

示例:

通过调用参数为"context, function name"的jQuery.proxy()方法,强制修改函数的上下文语境。 并且在第一次点击事件执行后,解除绑定。

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>


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


<script>


  var obj = {
    name: "John",
    test: function() {
      $("#log").append( this.name );
      $("#test").unbind("click", obj.test);
    }
  };

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


</script>
</body>
</html>

演示: