Last active
July 30, 2019 13:38
-
-
Save johnloy/f74570ff9c5f0e38eaad0d49d03e6fae to your computer and use it in GitHub Desktop.
State management with custom DOM events
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<script type="module"> | |
const createAction = (el, initialState, name, action) => { | |
let currentState = initialState; | |
document.body.addEventListener(name, (e) => { | |
el.render(e.detail.state); | |
}); | |
return (...args) => { | |
return (originalEvent) => { | |
const newState = action(currentState, ...args); | |
currentState = newState; | |
const event = new CustomEvent( | |
name, | |
{ | |
bubbles: true, | |
cancelable: false, | |
detail: { | |
state: newState, | |
originalEvent: originalEvent | |
} | |
} | |
); | |
el.dispatchEvent(event); | |
} | |
} | |
} | |
// Initialize message | |
const messageEl = document.querySelector('#message'); | |
const initialState = { | |
message: 'hi ' | |
}; | |
messageEl.render = function ({ message }) { | |
this.innerHTML = message; | |
} | |
messageEl.render(initialState); | |
const updateMessage = createAction( | |
messageEl, | |
initialState, | |
'UPDATE_MESSAGE', | |
(state, ...args) => { | |
state.message += 'hi '; | |
return state; | |
} | |
) | |
// Initialize button | |
const buttonEl = document.querySelector('#update-message'); | |
buttonEl.addEventListener('click', updateMessage()) | |
</script> | |
</head> | |
<body> | |
<div id="message"></div> | |
<button id="update-message">Update message</button> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment