cleanup dispatcher

This commit is contained in:
Feross Aboukhadijeh
2016-05-26 18:12:23 -07:00
parent 6e240b3fd4
commit 1aabd537d8

View File

@@ -1,41 +1,39 @@
module.exports = { module.exports = {
setDispatch,
dispatch, dispatch,
dispatcher dispatcher,
setDispatch
} }
// Memoize most of our event handlers, which are functions in the form var dispatchers = {}
// () => dispatch(<args>) var _dispatch = function () {}
// ... this prevents virtual-dom from updating every listener on every update()
var _dispatchers = {}
var _dispatch = () => {}
function setDispatch (dispatch) { function setDispatch (dispatch) {
_dispatch = dispatch _dispatch = dispatch
} }
// Get a _memoized event handler that calls dispatch() function dispatch (...args) {
// All args must be JSON-able _dispatch(...args)
}
// Most DOM event handlers are trivial functions like `() => dispatch(<args>)`.
// For these, `dispatcher(<args>)` is preferred because it memoizes the handler
// function. This prevents virtual-dom from updating the listener functions on
// each update().
function dispatcher (...args) { function dispatcher (...args) {
var str = JSON.stringify(args) var str = JSON.stringify(args)
var handler = _dispatchers[str] var handler = dispatchers[str]
if (!handler) { if (!handler) {
handler = _dispatchers[str] = function (e) { handler = dispatchers[str] = function (e) {
// Do not propagate click to elements below the button // Do not propagate click to elements below the button
e.stopPropagation() e.stopPropagation()
if (e.currentTarget.classList.contains('disabled')) { if (e.currentTarget.classList.contains('disabled')) {
// Do not allow clicks on disabled buttons // Ignore clicks on disabled elements
return return
} }
_dispatch.apply(null, args) dispatch(...args)
} }
} }
return handler return handler
} }
function dispatch (...args) {
_dispatch.apply(null, args)
}