|
1bba387
Scott Jehl authored
|
||
| 1 | /*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */ | |
| 2 | (function(){ | |
| 3 | // monkeypatch unsupported addListener/removeListener with polling | |
| 4 | if( !window.matchMedia( "" ).addListener ){ | |
| 5 | var oldMM = window.matchMedia; | |
| 6 | ||
| 7 | window.matchMedia = function( q ){ | |
| 8 | var ret = oldMM( q ), | |
| 9 | listeners = [], | |
| 10 | last = false, | |
| 11 | timer, | |
| 12 | check = function(){ | |
| 13 | var list = oldMM( q ); | |
| 14 | if( list.matches && !last ){ | |
| 15 | for( var i =0, il = listeners.length; i< il; i++ ){ | |
| 16 | listeners[ i ].call( ret, list ); | |
| 17 | } | |
| 18 | } | |
| 19 | last = list.matches; | |
| 20 | }; | |
| 21 | ||
| 22 | ret.addListener = function( cb ){ | |
| 23 | listeners.push( cb ); | |
| 24 | if( !timer ){ | |
| 25 | timer = setInterval( check, 1000 ); | |
| 26 | } | |
| 27 | }; | |
| 28 | ||
| 29 | ret.removeListener = function( cb ){ | |
| 30 | for( var i =0, il = listeners.length; i< il; i++ ){ | |
| 31 | if( listeners[ i ] === cb ){ | |
| 32 | listeners.splice( i, 1 ); | |
| 33 | } | |
| 34 | } | |
| 35 | if( !listeners.length && timer ){ | |
| 36 | clearInterval( timer ); | |
| 37 | } | |
| 38 | }; | |
| 39 | ||
| 40 | return ret; | |
| 41 | }; | |
| 42 | } | |
| 43 | }()); |