Files
webtorrent-desktop/renderer/lib/dispatcher.js
DC 5ae6d43e39 Memoize event handlers
Stop virtualdom from swapping out every event handler on every update
2016-03-27 02:58:26 -07:00

37 lines
904 B
JavaScript

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)
}