提议讨论:将绑定在 window 上的事???模块化拆分

大家好,

这里想抛一个想法,看看大家有没有兴趣一起讨论讨论:

我刚才在本地 Chrome 空白页里搜索了一下所有支持的事件:

Object.keys(window).filter(n => n.match(/^on/))
["ondeviceorientationabsolute", "ondeviceorientation", "ondevicemotion", "onunhandledrejection", "onrejectionhandled", "onunload", "onstorage", "onpopstate", "onpageshow", "onpagehide", "ononline", "onoffline", "onmessage", "onlanguagechange", "onhashchange", "onbeforeunload", "onwaiting", "onvolumechange", "ontoggle", "ontimeupdate", "onsuspend", "onsubmit", "onstalled", "onshow", "onselect", "onseeking", "onseeked", "onscroll", "onresize", "onreset", "onratechange", "onprogress", "onplaying", "onplay", "onpause", "onmousewheel", "onmouseup", "onmouseover", "onmouseout", "onmousemove", "onmouseleave", "onmouseenter", "onmousedown", "onloadstart", "onloadedmetadata", "onloadeddata", "onload", "onkeyup", "onkeypress", "onkeydown", "oninvalid", "oninput", "onfocus", "onerror", "onended", "onemptied", "ondurationchange", "ondrop", "ondragstart", "ondragover", "ondragleave", "ondragenter", "ondragend", "ondrag", "ondblclick", "oncuechange", "oncontextmenu", "onclose", "onclick", "onchange", "oncanplaythrough", "oncanplay", "oncancel", "onblur", "onabort", "onwheel", "onwebkittransitionend", "onwebkitanimationstart", "onwebkitanimationiteration", "onwebkitanimationend", "ontransitionend", "onsearch", "onanimationstart", "onanimationiteration", "onanimationend"]

发现里面的事件非常多,里面有相当一部分是和某些独立的 W3C JavaScript APIs Spec 强关联的,比如 onstorage 和 web storage API 规范相关联,ondevicemotion 和 device orientation event 规范相关联,onpopstate 和 History API 规范相关联。

所以:

1. 我觉得 window 这个对象有点“不堪重负”的感觉,将来一定还会有更多的事件被各种 JavaScript APIs 规范所定义,新的事件名称肯定越来越难定,难免相互“打架”
2. 我觉得 JavaScript APIs 的相关事件没有直接绑定在各自的对象上而是绑定在 window 上也不够直观,以 localStorage 为例,localStorage.setItem, localStorage.setItem, localStorage.addEventListener('change', ...) 或 localStorage.onchange 设计在一起更和谐一点,所有的操作都收敛到一个对象上,更有一种模块化的感觉
3. 现在绑定在 window 上的事件名字已经越来越长,而且好多都是多个单词连在一起,有些读写起来都很不直观了,其实也是有 namespace 的感觉的,比如 ondevicemotion 本质上信息量等价于 device.onmotion
4. 新的“模块化”的设计也易于未来新规范无环境差别的 polyfill

我的建议是把这些每份 JavaScript APIs 规范中的事件都尽量找到各自所属的对象,事件绑定就直接绑定在这个对象上,比如上述 localStorage 的例子

希望得到大家的建议和讨论

谢谢

Jinjiang

Received on Friday, 5 August 2016 16:36:00 UTC