-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (50 loc) · 1.44 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
import forIn from 'chirashi/src/core/for-in'
import resize from 'chirashi/src/events/resize'
import unresize from 'chirashi/src/events/unresize'
export class BreakpointListener {
constructor(breakpoints) {
this._current = ''
this._listeners = []
this._breakpoints = []
forIn(breakpoints, (key, value) => {
this._breakpoints.push({
size: value,
label: key
})
})
this._breakpoints.sort((a, b) => b.size - a.size)
this.resizeCallback = resize(this.resize.bind(this))
this.resize({
width: window.innerWidth
})
}
set current(value) {
if (this._current == value) return
this._current = value
this.trigger()
}
get current() {
return this._current
}
trigger() {
for (let listener of this._listeners) {
listener(this._current)
}
}
resize(size) {
let width = size.width,
i = this._breakpoints.length
while(i-- && width > this._breakpoints[i].size){}
this.current = this._breakpoints[Math.min(this._breakpoints.length-1, i+1)].label
}
on(callback) {
this._listeners.push(callback)
}
off(callback) {
this._listeners.splice(this._listeners.indexOf(callback), 1)
}
kill() {
unresize(this.resizeCallback)
}
}
export default BreakpointListener