Only fire an event once?

前端 未结 7 1857
谎友^
谎友^ 2020-11-27 06:06

How do I control only firing an event once?

Actually, a quick google appears to allude to the fact that .one helps..

相关标签:
7条回答
  • 2020-11-27 06:39

    You can use jQuery's one method, which will subscribe to only the first occurrence of an event.
    For example:

    $('something').one('click', function(e) {
        alert('You will only see this once.');
    });
    
    0 讨论(0)
  • 2020-11-27 06:39

    Slightly improved version of rofrol's anwser:

    function addEventListenerOnce(target, type, listener) {
        target.addEventListener(type, function fn() {
            target.removeEventListener(type, fn);
            listener.apply(this, arguments);
        });
    }
    

    By using apply all arguments are passed and the this works as expected.

    0 讨论(0)
  • 2020-11-27 06:43

    Same as rofrol's answer, just another form:

        function addEventListenerOnce(element, event, fn) {
            var func = function () {
                element.removeEventListener(event, func);
                fn();
            };
            element.addEventListener(event, func);
        }
    
    0 讨论(0)
  • 2020-11-27 07:00

    Just use proper option in your addEventListener method call:

    element.addEventListener(event, func, { once: true })
    
    0 讨论(0)
  • 2020-11-27 07:01

    Use once if you don't need to support Internet Explorer:

    element.addEventListener(event, func, { once: true });
    

    Otherwise use this:

    function addEventListenerOnce(target, type, listener, addOptions, removeOptions) {
        target.addEventListener(type, function fn(event) {
            target.removeEventListener(type, fn, removeOptions);
            listener.apply(this, arguments);
        }, addOptions);
    }
    
    addEventListenerOnce(document.getElementById("myelement"), "click", function (event) {
        alert("You'll only see this once!");
    });
    
    • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
    • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
    • http://www.sitepoint.com/create-one-time-events-javascript/
    • https://www.webreflection.co.uk/blog/2016/04/17/new-dom4-standards
    0 讨论(0)
  • 2020-11-27 07:01

    Added the options for add/remove event listener:

    function addEventListenerOnce(target, type, listener, optionsOrUseCaptureForAdd, optionsOrUseCaptureForRemove) {
        const f = event => {
            target.removeEventListener(type, f, optionsOrUseCaptureForRemove);
            listener(event);
        }
        target.addEventListener(type, f, optionsOrUseCaptureForAdd);
    }
    
    0 讨论(0)
提交回复
热议问题