$. Proxy () application example of jQuery _ jquery

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.