How powerful is $. proxy () in zepto ?, Zepto. proxy to the end
Well, it's actually the title party. Haha, I just want to summarize the usage of $. proxy () in my work.
I. Syntax:
$. Proxy () has two syntax types:
1) $. proxy (fn, context), fn is a function, and context is the context for executing the fn function.
For example:
Var obj = {name: 'zepto'}, handler = function () {alert (this. name)}; $ (document ). on ('click', $. proxy (handler, obj ));View Code
2) $. proxy (context, "fnName"). Note that fnName (function name) must be a string.
Var obj2 = {name: 'jquery ', age: 22, showAge: function () {alert (this. age) }}; $ (document ). on ('click', $. proxy (obj2, "showAge"); // pop up 22View Code
From the code above, we can see that $. proxy () is mainly usedChange the context of function executionNext, let's look at a practical example to actually use the benefits.
Ii. Practical examples:
Requirement: click the button with the id of myElement. After 1000 milliseconds, a class ('anewclass') is added to the element myElement ').
The following code may exist at the beginning, but we find that we cannot meet our needs.
$ ('# MyElement '). click (function () {setTimeout (function () {$ (this ). addClass ('anewclass'); // this points to the window at this time. Of course, you cannot add class}, 1000) to # myElement );});
To modify this point, we use $. proxy ()
$ ('# MyElement '). click (function () {setTimeout ($. proxy (function () {$ (this ). addClass ('anewclass') ;}, this), 1000); // at this time, this points to the clicked # myElement. Can you see it ?});