-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
109 lines (90 loc) · 2.46 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* Convenience wrapper for creating custom element prototypes.
*/
var symbol = require('es6-symbol')
var slice = require('sliced')
var clone = require('clone')
var uuid = require('uuid')
function noop(){}
var sym = symbol('custom-element')
var fns = [
'attributeChangedCallback',
'detachedCallback',
'attachedCallback',
'createdCallback'
]
module.exports = createCustom
function createCustom(proto) {
proto = proto || HTMLElement.prototype
var CustomHTMLElement = Object.create(proto)
var listeners = CustomHTMLElement.listeners = clone(CustomHTMLElement.listeners || {})
var oldListeners = backupListeners(CustomHTMLElement)
attach('attributeChangedCallback', 'attribute')
attach('detachedCallback', 'detached')
attach('attachedCallback', 'attached')
attach('createdCallback', 'created')
var onceKey = '__once__' + uuid()
var onces = 0
var exported = {
on: listen
, once: listenOnce
, prototype: CustomHTMLElement
, use: use
}
return exported
function on(key) {
function attachListener() {
var self = this
var args = slice(arguments)
var fire = listeners[key]
if (listeners && listeners[key]) {
fire.forEach(function(fn) {
fn.apply(self, args)
})
}
return this
}
// this is a unique identifier
// so we can check if it's a
// function generated by `.on()`
attachListener[sym] = true
return attachListener
}
function use(fn) {
fn && fn(exported)
return exported
}
function listen(key, listener) {
listeners[key] = listeners[key] || []
listeners[key].push(listener)
return exported
}
// We have to set a property directly on the instance
// to avoid "once" being scoped to *every* instance of
// an element. In the future, a hypothetical
// "prototype-emitter" module could make this nicer and
// more performant.
function listenOnce(key, listener) {
var hasEmitted = onceKey + onces++
return listen(key, function() {
if (this[hasEmitted]) return
this[hasEmitted] = true
return listener.apply(this
, slice(arguments)
)
})
}
function backupListeners(obj) {
var backup = {}
fns.forEach(function(key) {
var cb = obj[key]
if (cb && !cb[sym]) backup[key] = cb
})
return backup
}
function attach(key, event) {
CustomHTMLElement[key] = on(event)
var listener = oldListeners[key]
if (listener) listen(event, listener)
}
}