jQuery.proxy()的用法

我正在阅读关于jQuery.proxy()的api。 它看起来很有希望,但我想知道在什么情况下这是最好的使用。 任何人都可以启发我吗?

当你想要一个函数将this值绑定到一个特定的对象。 例如,在callback中,如事件处理程序,AJAXcallback,超时,间隔,自定义对象等

这只是一个可能有用的情况的例子。 假设有一个具有属性名称的Person对象。 它也链接到一个文本input元素,并且每当input值改变时,这个人物对象的名字也被更新。

 function Person(el) { this.name = ''; $(el).change(function(event) { // Want to update this.name of the Person object, // but can't because this here refers to the element // that triggered the change event. }); } 

我们经常使用的一个解决scheme是将这个上下文存储在一个variables中,并在callback函数中使用它,例如:

 function Person(el) { this.name = ''; var self = this; // store reference to this $(el).change(function(event) { self.name = this.value; // captures self in a closure }); } 

或者,我们可以在这里使用jQuery.proxy ,所以引用this指的是Person的对象,而不是触发事件的元素。

 function Person(el) { this.name = ''; $(el).change(jQuery.proxy(function(event) { this.name = event.target.value; }, this)); } 

请注意,此function已经标准化到ECMAScript 5中,该function现在包含从prototypejs借用的bind方法,并且已经在某些浏览器上可用。

 function Person(el) { this.name = ''; $(el).change(function(event) { this.name = event.target.value; }.bind(this)); // we're binding the function to the object of person } 

这只是设置闭包的上下文的简写方法,例如:

 $(".myClass").click(function() { setTimeout(function() { alert(this); //window }, 1000); }); 

然而,我们经常希望this和我们使用的$.proxy()方法保持一致,如下所示:

 $("button").click(function() { setTimeout($.proxy(function() { alert(this); //button }, this), 1000); });​ 

它通常用于延迟调用,或者任何你不想做一个宣布闭包的长效方法的地方。 将上下文指向对象的string方法…嗯,我还没有在每天的代码中遇到实际的使用,但我确定有应用程序,只是取决于你的对象/事件结构。

例如,如果你想创buildcallback。 代替:

 var that = this; $('button').click(function() { that.someMethod(); }); 

你可以做:

 $('button').click($.proxy(this.someMethod, this)); 

或者,如果您创build一个接受callback的插件,并且您必须为该callback设置特定的上下文。