3

Is there some kind of way to clear onClick listeners on a button in Dart HTML that doesn't require keeping track of all the listeners?

This code is executed each time a certain div is made visible and onClick listeners are attached to certain buttons, if it's hidden and shown again, more onClick listeners are attached and the old onClick event which is no longer valid is also being called.

querySelectorAll("button.update-something").forEach((ButtonElement b) {
    b.onClick.listen((e) {
        // Do Stuff
    });
}

Is there a way to clear existing onClick listeners or override the existing onClick listener without having to keep track of previous onClick listeners?

Jan Vladimir Mostert
  • 12,380
  • 15
  • 80
  • 137

1 Answers1

1

With keeping track you probably mean

List<StreamSubscriptions> subscriptions = [];

querySelectorAll("button.update-something").forEach((ButtonElement b) {
    subscriptions.add(b.onClick.listen((e) {
        // Do Stuff
    }));
}

I guess this is what you are looking for

querySelectorAll("button.update-something").forEach((ButtonElement b) {
    b.addEventListener('click', clickHandler);
}

void clickHandler(e) {
  // Do stuff
}

querySelectorAll("button.update-something").forEach((ButtonElement b) {
    b.removeEventListener('click', clickHandler);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Using addEventListener and removeEventListener, it seems you now have to sacrifice the anonymous event listener. If that's the case, I'll stick to tracking the listeners. Thanks Gunter! – Jan Vladimir Mostert Aug 30 '15 at 12:05
  • I haven't used this method myself yet, but I suspected that equality comparison might not work with inline functions, therefore I used the named function variant in my answer to be on the safe side. Should be easy to try if it also works with anonymous functions. – Günter Zöchbauer Aug 30 '15 at 12:09
  • 1
    Thanks to dart's awesome syntax, unsubscribing all those subscriptions when tracking can be done using: `subscriptions..forEach((StreamSubscription sub) => sub.cancel())..clear();` – Jan Vladimir Mostert Aug 30 '15 at 12:42
  • Ok, I thought this was what you meant by "tracking" and what you want to avoid. – Günter Zöchbauer Aug 30 '15 at 12:50
  • 1
    Yes, I was looking for something simpler like `b.onClick.listeners.clear()`, assuming `addEventListener` and `removeEventListener` is the only other way to do it, I'd rather stick with the subscription way of doing it, seems cleaner than having to deal with "low-level" javascript events. – Jan Vladimir Mostert Aug 30 '15 at 12:59