Home >Web Front-end >JS Tutorial >jquery one function method implementation

jquery one function method implementation

巴扎黑
巴扎黑Original
2017-06-25 11:13:041895browse

There is a method in

jquery: one, which is used to EventThe 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;
    })
}


This method is possible, but there is a problem, Event processingFunction It 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 if anonymous function is used, it will fall into terrible infinite recursion.

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

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!

Statement:
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