jQuery中$.proxy()使用整理

来源:互联网 发布:代理服务器软件下载 编辑:程序博客网 时间:2024/06/05 02:52

$.proxy 方法接受一个已有的函数,并返回一个带特定上下文的新的函数

1.jQuery.proxy( function, context )

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

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

test=function(){this.txt="This is an object property";$("div").click($.proxy(this.myClick,this));};test.prototype.myClick = function(event){alert(this.txt);alert(event.currentTarget.);};

2.jQuery.proxy( context, name )

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

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

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

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

  var objPerson = {    name: "John Doe",    age: 32,    test: function(){      $("p").after("Name: " + this.name + "<br> Age: " + this.age);    }  };  $("button").click($.proxy(objPerson,"test"));

其他实例代码

$('#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() {    setTimeout($.proxy(function() {        $(this).addClass('aNewClass');  // Now "this" is again our element    }, this), 1000);});




 

0 0
原创粉丝点击