Home > Web Front-end > JS Tutorial > body text

jQuery's $.proxy() application example introduction_jquery

WBOY
Release: 2016-05-16 16:53:24
Original
1051 people have browsed it

Today I saw the use of proxy() when I was watching <>. It felt very vague, so I looked for information everywhere.

jQuery's $.proxy() application example introduction_jquery

The source code of jQuery is also I don’t understand.

But I finally understand the usage of proxy;

Copy the code The code is as follows:



Copy code The code is as follows:

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

From above proxy(a,b ) can be seen that there are two ways to write its parameters.

The first way: a is a function function, and b is the object owner of this function.

The second way: a is an object, b is a string, and is the attribute name of a.

And this example is an example on <>.
Copy code The code is as follows:



Copy code 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.
Copy code The code is as follows:

$("#panel").fadeIn(function ( ) {
var obj = this;
$("#panel button").click($.proxy(function () {
$(this).fadeOut();
}, obj ));
});

The panel will disappear only after clicking the button.

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

is encapsulated on the basis of apply, so proxy is our jQuery’s own apply.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template