Created
October 6, 2017 10:36
-
-
Save pirate/50fc34fd69f6698079dfa4bf917c26b5 to your computer and use it in GitHub Desktop.
Adding and removing reducers to redux dynamically using an event listener system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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