Created
June 18, 2017 13:47
-
-
Save bga/4804c72c510b2d16a2c26039e1471d79 to your computer and use it in GitHub Desktop.
handleEventVsLambdaStyle.js
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
//# "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