Memoize event handlers

Stop virtualdom from swapping out every event handler on every update
This commit is contained in:
DC
2016-03-27 00:55:42 -07:00
parent 8e344bed20
commit 3617c17300
6 changed files with 125 additions and 94 deletions

View File

@@ -0,0 +1,36 @@
module.exports = {
setDispatch,
dispatch,
dispatcher
}
// _memoize most of our event handlers, which are functions in the form
// () => dispatch(<args>)
// ... this prevents virtual-dom from updating tons of listeners on every update()
var _dispatchers = {}
var _dispatch = () => {}
function setDispatch (dispatch) {
_dispatch = dispatch
}
// Get a _memoized event handler that calls dispatch()
// All args must be JSON-able
function dispatcher (...args) {
var json = JSON.stringify(args)
var handler = _dispatchers[json]
if (!handler) {
_dispatchers[json] = (e) => {
// Don't click on whatever is below the button
e.stopPropagation()
// Don't regisiter clicks on disabled buttons
if (e.target.classList.contains('disabled')) return
_dispatch.apply(null, args)
}
}
return handler
}
function dispatch (...args) {
_dispatch.apply(null, args)
}