Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active December 23, 2015 16:59
Show Gist options
  • Save mindplay-dk/6665405 to your computer and use it in GitHub Desktop.
Save mindplay-dk/6665405 to your computer and use it in GitHub Desktop.
Simple event hook in TypeScript
var template_escape = {"\\": "\\\\", "\n": "\\n", "\r": "\\r", "'": "\\'"}
var render_escape = {'&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;'}
function escape_fn(data) {
return (data || data === 0)
? (data + '').replace(/[&\"<>]/g, (e) => render_escape[e])
: ''
}
function no_escape_fn(data) {
return (data || data === 0)
? (data + '')
: ''
}
interface Template<T> {
(data: T): string
}
function template<T>(tmpl): Template<T> {
var render = new Function("_", "e", "$e", "return '" +
tmpl
.replace(/[\\\n\r']/g, (escape) => template_escape[escape])
.replace(/{(\$?)\s*([\w\.]+)\s*}/g,
"'+(function(){try{return $1e(_.$2)}catch(e){return ''}})()+'") + "'"
)
return function (data) {
return render(data, escape_fn, no_escape_fn)
}
}
var tpl = template<{ foo: string; bar: string }>('<foo>{foo}</foo><bar>{$bar}</bar>');
console.log(tpl({foo: "Hello & World", bar: "Hello &nbsp; World"}))
//
interface Hook<Event> {
(handler: { (event: Event): void }): void
(event: Event): void
}
function hook<Event>(): Hook<Event> {
var _handlers: Array<Function> = []
var _busy = false
function invoke() {
if (arguments[0] instanceof Function) {
_handlers.push(arguments[0]);
} else if (!_busy) {
_busy = true
for (var i = 0; i < _handlers.length; i++) {
_handlers[i].apply(this, arguments)
}
_busy = false
}
}
return <Hook<Event>> invoke;
}
// EXAMPLE:
interface LoginEvent {
username: string
success: boolean
}
var onLogin = hook<LoginEvent>()
onLogin(event => console.log("Logged in: " + event.username))
onLogin({ username: 'Rasmus', success: true })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment