jquery one function method implementation

巴扎黑
Release: 2017-06-25 11:13:04
Original
1739 people have browsed it

There is a method in

jquery: one, which is used toEventThe binding is only executed once and then automatically unbinded. I felt dizzy after looking at the source code for a long time, so I decided to make one myself. After studying it for a long time, I simulated it once using native. The name I used was once.

The original method is like this:

function once(dom, event, callback) { // 这一步是为了避免修改形参 var temp = callback; dom.addEventListener(event, function() { if(temp) temp(); temp = null; }) }
Copy after login


This method is possible, but there is a problem,Event processingFunctionIt still exists, but nothing is executed, and it will become very bloated over time.

The alternative is to cancel itself in the handler function, but ifanonymous functionis used, it will fall into terrible infiniterecursion.

It can be solved by using variable storage.

function once(dom, event, callback) { var handle = function() { callback(); dom.removeEventListener(event, handle); } dom.addEventListener(event, handle) }
Copy after login

This is a piece of leisure entertainment, I hope it can help some people.

The above is the detailed content of jquery one function method implementation. For more information, please follow other related articles on the PHP Chinese website!

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!