forked from FrontendMatter/material-design-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedia-query.js
More file actions
71 lines (59 loc) · 1.32 KB
/
Copy pathmedia-query.js
File metadata and controls
71 lines (59 loc) · 1.32 KB
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
import { watch, unwatch } from 'watch-object'
/**
* Bind to a CSS media query
* @param {String} query The CSS media query
* @return {Object}
*/
export const mediaQuery = (query) => {
let mediaQuery = {
// The CSS media query
query,
// CSS media query matches
queryMatches: null,
_reset () {
this._removeListener()
this.queryMatches = null
if (!this.query) {
return
}
this._mq = window.matchMedia(this.query)
this._addListener()
this._handler(this._mq)
},
_handler (mq) {
this.queryMatches = mq.matches
},
_addListener () {
if (this._mq) {
this._mq.addListener(this._handler)
}
},
_removeListener () {
if (this._mq) {
this._mq.removeListener(this._handler)
}
this._mq = null
},
/**
* Initialize mediaQuery
*/
init () {
watch(this, 'query', this._reset)
this._reset()
},
/**
* Destroy mediaQuery
* @return {[type]} [description]
*/
destroy () {
unwatch(this, 'query', this._reset)
this._removeListener()
}
}
// Bind handlers
mediaQuery._reset = mediaQuery._reset.bind(mediaQuery)
mediaQuery._handler = mediaQuery._handler.bind(mediaQuery)
// Initialize mediaQuery
mediaQuery.init()
return mediaQuery
}