-
-
Notifications
You must be signed in to change notification settings - Fork 156
/
MediaQuery.js
74 lines (67 loc) · 1.32 KB
/
MediaQuery.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
/* CSS media query listener.
*
* Extend from Emitter.
*
* ### constructor
*
* |Name |Desc |
* |-----|-----------|
* |query|Media query|
*
* ### setQuery
*
* Update query.
*
* ### isMatch
*
* Return true if given media query matches.
*
* ### Events
*
* #### match
*
* Triggered when a media query matches.
*
* #### unmatch
*
* Opposite of match.
*/
/* example
* const mediaQuery = new MediaQuery('screen and (max-width:1000px)');
* mediaQuery.isMatch(); // -> false
* mediaQuery.on('match', () => {
* // Do something...
* });
*/
/* module
* env: browser
* since: 1.5.2
*/
/* typescript
* export declare class MediaQuery extends Emitter {
* constructor(query: string);
* setQuery(query: string): void;
* isMatch(): boolean;
* }
*/
_('Emitter');
exports = Emitter.extend({
className: 'MediaQuery',
initialize(query) {
this.callSuper(Emitter, 'initialize');
this._listener = () => {
this.emit(this.isMatch() ? 'match' : 'unmatch');
};
this.setQuery(query);
},
setQuery(query) {
if (this._mql) {
this._mql.removeListener(this._listener);
}
this._mql = window.matchMedia(query);
this._mql.addListener(this._listener);
},
isMatch() {
return this._mql.matches;
}
});