How powerful is $. proxy () in zepto ?, Zepto. proxy to the end

Source: Internet
Author: User

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 ?});

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.