JQuery's $.proxy of application examples

  • 2020-03-30 02:31:04
  • OfStack

Watching today < < Sharp jQuery> > When I saw the use of proxy(), I felt very vague and looked for information everywhere.

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201404/20140403154145.jpg? 201433154214 ">  

JQuery source also did not see.

But I've finally figured out how to use proxy;
 
<input type="button" value=" test " id="guoBtn" name=" I'm a button name"/> 

 
var obj = { 
name: " I am a obj the name", 
sayName: function () { 
alert(this.name); 
} 
} 
$("#guoBtn").click(obj.sayName); //I'm the name of the button
//What if I want to access obj's name?
$("#guoBtn").click($.proxy(obj.sayName,obj));//"I'm the name of obj."
$("#guoBtn").click($.proxy(obj, "sayName")); //"I'm the name of obj."

From the above usage of proxy(a,b), it can be seen that there are two ways to write his parameters.

First :a is a function and b is the object owner of the function.

The second :a is an object, and b is a string, which is the property name of a.

Another example is < < Sharp jQuery> > An example of that.
 
<div id="panel" style="display:none;"> 
<button>Close</button> 
</div> 

 
$("#panel").fadeIn(function () { 
$("#panel button").click(function () { 
$(this).fadeOut(); 
}); 
}); 


The button disappears, but the panel does not. The proxy can be used to solve this problem.
 
$("#panel").fadeIn(function () { 
var obj = this; 
$("#panel button").click($.proxy(function () { 
$(this).fadeOut(); 
}, obj)); 
}); 

The panel disappears after the button is clicked.

Personally, proxy is mainly used to modify the context object when the function is executed.

The encapsulation is done on the basis of apply, so proxy is our own jQuery apply.

Related articles: