Anonymous functions of javascrpt binding events cannot be unbound _ basic knowledge

Source: Internet
Author: User
It is often said that the anonymous function binding event is difficult to control and cannot be unbound. This article will introduce the detailed solution. If you need it, you can refer to it and often hear someone say, the anonymous function binding event is difficult to control, and cannot be unbound. It's always strange who said it cannot be unbound.

Click the event twice and then unbind it automatically.

View code:

The Code is as follows:


Var dom = document. getElementById ("test"), clickt = 0;
Dom. addEventListener ("click", function (e ){
Clickt ++;
Alert ('You touched me '+ clickt +. Touch up to 2 times ');
If (clickt> = 2 ){
This. removeEventListener (e. type, arguments. callee, false );
}
});


Many extension libraries, such as jquery, can achieve custom unbinding:

The Code is as follows:


Var t = 0;
$ (". A"). bind ("click", function (e ){
T ++;
Alert ('You touched me '+ t +. Touch up to 2 times ');
If (t> = 2 ){
$ (This). unbind (e. type, arguments. callee );
}
});


Let's test it for others.
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.