I'm using etherum.on listeners and would like to remove them as advised by the documentation, however the ethereum.removeListener does not work.
I am using js not ts.
How to remove the event listener? Here is my initial code (which works fine and detects changes):
ethereum.on('accountsChanged', (accounts) => {
if (accounts.length > 0) {
walletTxt.innerText = 'Connected: 0x..' + accounts[0].slice(-3);
walletTxt.style.color = "#AAFF00";
notyf.success(walletTxt.innerText);
balanceJoo();
} else {
unlocked();
walletBtn.disabled = false;
updateButton();
}
});
Here is the updated code as requested by documentation (Not working in the sense that does not detect anything):
function handleAccountsChanged(accounts) {
if (accounts.length > 0) {
walletTxt.innerText = 'Connected: 0x..' + accounts[0].slice(-3);
walletTxt.style.color = "#AAFF00";
notyf.success(walletTxt.innerText);
balanceJoo();
} else {
unlocked();
walletBtn.disabled = false;
updateButton();
}
}
// Register the event listener
ethereum.on('accountsChanged', handleAccountsChanged);
// Later, remove the event listener
ethereum.removeListener('accountsChanged', handleAccountsChanged);
Any suggestion on how to remove the listener correctly? Also would like to know, will the listener stops when a new page is loaded?
Update, I also tried:
window.addEventListener("load", function() {
accounts = ethereum.request({
method: 'eth_accounts'
}).then((result) => {
console.log(result)
});
function handleAccountsChanged(accounts) {
console.log('Account changed: ' + accounts);
}
ethereum.on('accountsChanged', handleAccountsChanged); //Works
// ethereum.removeListener('accountsChanged', handleAccountsChanged);
})
window.addEventListener("load", function() {
accounts = ethereum.request({
method: 'eth_accounts'
}).then((result) => {
console.log(result)
});
function handleAccountsChanged(accounts) {
console.log('Account changed: ' + accounts);
}
ethereum.on('accountsChanged', handleAccountsChanged); // Stops Working with remove listense uncommeted
ethereum.removeListener('accountsChanged', handleAccountsChanged);
})