Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. import { forOwn } from 'lodash'
  2.  
  3. export default class MediaDetector {
  4. constructor (layouts, fn) {
  5. this.callback = fn
  6. this.state = null
  7. this.listeners = []
  8.  
  9. this.listen = this.listen.bind(this)
  10. this.setListener = this.setListener.bind(this)
  11.  
  12. forOwn(layouts, this.setListener)
  13. }
  14.  
  15. destroy () {
  16. this.listeners.forEach(listener => {
  17. listener.match.removeListener(listener.fn)
  18. })
  19. this.listeners = []
  20. }
  21.  
  22. setListener (type, key) {
  23. const match = window.matchMedia(key)
  24. const typedListener = this.listen.bind(this, type)
  25.  
  26. typedListener(match)
  27. match.addListener(typedListener)
  28.  
  29. this.listeners.push({
  30. match,
  31. fn: typedListener
  32. })
  33. }
  34.  
  35. listen (type, match) {
  36. if (match.matches) {
  37. if (this.state !== type) {
  38. this.state = type
  39. this.callback(this.state)
  40. }
  41. }
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement