I am watching Dan Abramov's Redux tutorial on Egghead, and he does something that I am a little confused by. As a learning exercise, he has viewers rebuild the createStore
abstraction. One method createStore
provides is subscribe
, which adds listeners to listen for store changes.
He then says:
There is an important missing piece here. We haven't provided a way to unsubscribe a listener. Instead of adding a dedicated Unsubscribe method, we'll just return a function from the Subscribe method that removes this listener from the listeners' array.
So the code he uses to add/remove the listener is:
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
};
};
I sort of understand that this allows you to use one function for both add/remove, and that this is possible because if you pass the subscribe method the name of a listener that is already subscribed, the filter will remove it, I do not understand why this returns an arrow function rather than an array of listeners. How/when would this returned function be invoked?
Using the removeEventListener() method The JavaScript built-in function removeEventListener() removes an event handler from an element for a connected event. For instance, you can use removeEventListener() to get rid of a click event listener if a button is disabled after one click.
Keeping events alive Since we only need the listener for our modal, it should be removed whenever the user cannot interact with our modal any longer. The same is true for any element that can be toggled as well as animations on elements.
To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.
How/when would this returned function be invoked?
This function is invoked when the listener should be removed. When exactly this should happen depends on the app.
Invocation is simple:
const remove = subscribe(myListener);
// later:
remove();
I do not understand why this returns an arrow function rather than an array of listeners.
That would allow any subscriber to mess with the listeners array, or requires every subscriber to implement the same unsubscribe logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With