Last active
December 23, 2015 16:59
-
-
Save mindplay-dk/6665405 to your computer and use it in GitHub Desktop.
Simple event hook in TypeScript
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 template_escape = {"\\": "\\\\", "\n": "\\n", "\r": "\\r", "'": "\\'"} | |
var render_escape = {'&': '&', '"': '"', '<': '<', '>': '>'} | |
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 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