Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fwojciec/f49cc303b4599922b0c6d2618bd9dc50 to your computer and use it in GitHub Desktop.
Save fwojciec/f49cc303b4599922b0c6d2618bd9dc50 to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/kulujin
// this pattern subscribes adds item to an array when subscribe function
// is is assigned to a variable, and unsubscribes when this variable is eventually called
// taken from Redux tutorial
// https://egghead.io/lessons/react-redux-implementing-store-from-scratch
// also discussed here
// https://stackoverflow.com/questions/35304790/es6-redux-returning-a-function-to-remove-event-listener
let listeners = []
function subscribe(listener) {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
};
};
const remove = subscribe('myListener');
console.log(listeners) // myListener in the array
remove()
console.log(listeners) // myListener no longer in the array
// pretty cool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment