Skip to content

Instantly share code, notes, and snippets.

@bga
Created June 18, 2017 13:47
Show Gist options
  • Save bga/4804c72c510b2d16a2c26039e1471d79 to your computer and use it in GitHub Desktop.
Save bga/4804c72c510b2d16a2c26039e1471d79 to your computer and use it in GitHub Desktop.
handleEventVsLambdaStyle.js
//# "Class" style
class MyWidgit {
var root = null;
handleEvent(ev) {
//# imagine 10 types and 20 subelements - it will be 500sloc bloody mess
switch(ev.type) {
case("click") {
alert("you clicked me!")
} break;
case("input") {
switch(ev.target) {
case(root.inputAria) {
} break;
default: {
}
}
} break;
default: {
}
}
}
regEventListeners() {
//# dont forget ALL types that in { switch } below
root.addEventListener("click", this)
root.addEventListener("input", this)
}
}
//# we defenitaly need some DSL for that hand written { switch } router
//# kinda this
class MyWidgit {
var root = null;
onClick(ev) {
alert("you clicked me!")
}
handleEvent(ev) {
//# { "click" } -> { "onClick" }
return this["on" + ev.type[0].toUpperCase() + ev.type.slice(1)].apply(this, [ev])
}
regEventListeners() {
const thisProto = Object.getPrototypeOf(this)
var alreadyRegistredTypes = new Set()
for(var memberName in thisProto) {
if(Object(thisProto[memberName]) instanceof Function) {
const methodName = memberName
//# event handler
if(methodName.match(/^on[A-Z]/) != null) {
//# { "onClick" } -> { "click" }
const eventType = methodName.slice(2).toLowerCase()
if(alreadyRegistredTypes.has(eventType)) {
}
else {
root.addEventListener(eventType, this)
alreadyRegistredTypes.add(eventType)
}
}
else {
}
}
else {
}
}
}
}
// vs avg js coder' style
// crude, short, no boilerplate. Has memory leaks but JS engine' GC is "smart"
class MyWidgit {
var root = null;
regEventListeners() {
//# looks kinda declarative
root.addEventListener("click", function() {
alert("you clicked me!")
})
root.inputAria.addEventListener("input", function(ev) {
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment