Make redraw monolithic, add m.redraw.sync

This commit is contained in:
Pierre-Yves Gérardy 2017-06-13 15:35:05 +02:00
parent b004c20f0c
commit ccb3d61675

View file

@ -19,26 +19,32 @@ function throttle(callback) {
} }
} }
module.exports = function($window, throttleMock) { module.exports = function($window, throttleMock) {
var _throttle = throttleMock || throttle
var renderService = coreRenderer($window) var renderService = coreRenderer($window)
renderService.setEventCallback(function(e) { renderService.setEventCallback(function(e) {
if (e.redraw !== false) redraw() if (e.redraw !== false) redraw()
}) })
var callbacks = [] var callbacks = []
var rendering = false
function subscribe(key, callback) { function subscribe(key, callback) {
unsubscribe(key) unsubscribe(key)
callbacks.push(key, _throttle(callback)) callbacks.push(key, callback)
} }
function unsubscribe(key) { function unsubscribe(key) {
var index = callbacks.indexOf(key) var index = callbacks.indexOf(key)
if (index > -1) callbacks.splice(index, 2) if (index > -1) callbacks.splice(index, 2)
} }
function redraw() { function sync() {
for (var i = 1; i < callbacks.length; i += 2) { if (rendering) throw new Error("Nested m.redraw.sync() call")
callbacks[i]() rendering = true
} for (var i = 1; i < callbacks.length; i+=2) try {callbacks[i]()} catch (e) {/*noop*/}
rendering = false
} }
var redraw = (throttleMock || throttle)(sync)
redraw.sync = sync
return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render} return {subscribe: subscribe, unsubscribe: unsubscribe, redraw: redraw, render: renderService.render}
} }