This article mainly introduces the $. proxy () Application of jQuery. For more information, see < <锋利的jquery> > When I saw the use of proxy (), I felt very vague, so I went around to find information.
JQuery's source code is not clear.
But I finally understood the proxy usage;
The Code is as follows:
The Code is as follows:
Var obj = {
Name: "My name is obj ",
SayName: function (){
Alert (this. name );
}
}
$ ("# GuoBtn"). click (obj. sayName); // The name Of The button
// What if I want to access the obj name?
$ ("# GuoBtn"). click ($. proxy (obj. sayName, obj); // "name of obj"
$ ("# GuoBtn"). click ($. proxy (obj, "sayName"); // "name of obj"
From the usage of proxy (a, B) above, we can see that there are two ways to write his parameters.
First, a is a function, and B is the object owner of the function.
Type 2: a is an object, B is a string, and is the attribute name of.
And this instance is < <锋利的jquery> > Here is an example.
The Code is as follows:
Close
The Code is as follows:
$ ("# Panel"). fadeIn (function (){
$ ("# Panel button"). click (function (){
$ (This). fadeOut ();
});
});
Although the button disappears, the panel does not disappear. You can use proxy to solve this problem.
The Code is as follows:
$ ("# Panel"). fadeIn (function (){
Var obj = this;
$ ("# Panel button"). click ($. proxy (function (){
$ (This). fadeOut ();
}, Obj ));
});
In this way, the panel disappears after you click the button.
In my opinion, proxy is mainly used to modify the context object during function execution.
Is the encapsulation Based on the apply, so proxy is our jQuery's own apply.