gpt4 book ai didi

javascript - 如何确保事件只添加一次?

转载 作者:行者123 更新时间:2023-11-27 22:34:41 25 4
gpt4 key购买 nike

我想检查是否每次 URL 更改时都会触发一个事件。因为没有 Pushstate 事件,所以我遵循此建议 How to get notified about changes of the history via history.pushState?

(function(history) {
var pushState = history.pushState;
history.pushState = function(state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({
state: state
});
}
return pushState.apply(history, arguments);
}

function e(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
}
window.addEventListener('popstate', e);
history.onpushstate = e;
})(window.history)

但是,我的库允许多个实例。如果我多次初始化库,我会根据库初始化的次数收到消息。即使我多次运行该代码片段,我是否可以确保只附加一个事件?

最佳答案

实现此目的的一种方法可能是使用中间对象。这种方法允许您控制要删除的实例中的事件,并且可以轻松扩展到其他类似的用例。我添加了一个公共(public) isBound bool 值,以防您想要验证事件是否已订阅的实例。

(function(history) {
var pushState = history.pushState;

function e(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
}

function proxyPopstateEvent (evt) {
history.pushState = function(state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({
state: state
});
}
return pushState.apply(history, arguments);
}

var proxy = function (e) {
this.event = e;
this.isBound = false;

this.bindPopstateEvent = function() {
window.addEventListener('popstate', this.event);
history.onpushstate = this.event;
this.isBound = true;
}

this.removePopstateEvent = function() {
window.removeEventListener('popstate', this.event);
history.onpushstate = {};
}
};
window.popstateEventProxy = new proxy(evt);
window.popstateEventProxy.bindPopstateEvent();
}

if (!window.popstateEventProxy) {
proxyPopstateEvent(e);
}
})(window.history)

关于javascript - 如何确保事件只添加一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com