开发者

Only fire an event once?

How do I control only firing an event once?

Actually, a qu开发者_运维知识库ick Google appears to allude to the fact that .one helps..


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


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.');
});


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


Just use proper option in your addEventListener method call:

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


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.


Additionally, you can do this:

window.addEventListener("click", function handleClick(e) {
    window.removeEventListener("click", handleClick);

    // ...
});


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜