Last active
December 17, 2015 23:39
-
-
Save darsain/5691224 to your computer and use it in GitHub Desktop.
Buffered logging into HTML element.
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
var slice = [].slice; | |
function escape (value) { | |
escape.el.innerText = value; | |
return escape.el.innerHTML; | |
} | |
escape.el = document.createElement('pre'); | |
function Buffer(frame, size) { | |
if (!(this instanceof Buffer)) { | |
return new Buffer(frame, size); | |
} | |
if (typeof frame === 'number') { | |
size = frame; | |
frame = null; | |
} | |
this.frame = frame ? frame : document.createElement('pre'); | |
this.buffer = []; | |
this.size = size = 0|size || 10; | |
while (size--) { | |
this.buffer.push(''); | |
} | |
var self = this; | |
this.render = function () { | |
self._render(); | |
}; | |
} | |
Buffer.prototype.requestRender = function requestRender () { | |
if (this._renderID) { | |
return; | |
} | |
this._renderID = setTimeout(this.render, 17); | |
}; | |
Buffer.prototype._render = function _render () { | |
this._renderID = 0; | |
var scroll = this.frame.scrollHeight - this.frame.clientHeight === this.frame.scrollTop; | |
this.frame.innerHTML = this.buffer.join('<br>'); | |
if (scroll) this.frame.scrollTop = this.frame.scrollHeight; | |
}; | |
Buffer.prototype.insert = function insert (type, data) { | |
this.buffer.shift(); | |
this.buffer.push('<span class="' + type + '">' + slice.call(data).map(escape).join(', ') + '</span>'); | |
this.requestRender(); | |
}; | |
Buffer.prototype.log = function log () { | |
this.insert('log', arguments); | |
}; | |
Buffer.prototype.error = function error () { | |
this.insert('error', arguments); | |
}; |
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
<pre id="buffer"></pre> | |
<script> | |
// Pass buffer container element and buffer size as arguments | |
// new keyword is optional | |
var buffer = new Buffer(document.querySelector('#buffer'), 10); | |
// write line | |
buffer.log('foo'); | |
// extend buffer with more line types | |
Buffer.prototype.warning = function warning () { | |
this.insert('warning', arguments); | |
}; | |
// and use them | |
buffer.warning('foo', 'bar', 'baz'); | |
// buffer will write 10 last lines in chronological order | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment