Skip to content

Instantly share code, notes, and snippets.

@pirate
Created October 6, 2017 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirate/50fc34fd69f6698079dfa4bf917c26b5 to your computer and use it in GitHub Desktop.
Save pirate/50fc34fd69f6698079dfa4bf917c26b5 to your computer and use it in GitHub Desktop.
Adding and removing reducers to redux dynamically using an event listener system
import {desktopNotify, requestDesktopNotify} from '@/util/browser'
// when user clicks "notify me" checkbox
requestDesktopNotify()
store.dispatch({
type: 'ADD_EVENT_LISTENER',
pattern: 'ALERT',
handler: (action) => {
if (action.alert.subtype == 'sit_in')
desktopNotify(action.alert.message)
},
})
const actionMatchesListener = (listener, action) => {
// exact string pattern
if (typeof(listener.pattern) === 'string')
return listener.pattern === action.type
// regex pattern
if (listener.pattern.test))
return listener.pattern.test(action.type)
// function pattern
if (typeof(listener.pattern === 'function'))
return listener.pattern(action)
}
const matchingListeners = (listeners, action) =>
Object.values(listeners).filter(listener =>
actionMatchesListener(action, listener))
const eventsReducer = (state, action) => {
switch(action.type) {
case 'ADD_EVENT_LISTENER':
const len = Object.keys(state).length
return {
...state,
[action.id || len]: action.handler,
}
default:
// run all redux actions through eventListeners
for (let listener of matchingListeners(state, action)) {
listener.handler(action)
}
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment