Skip to content
Browse files

Added an external extension for addListener and removeListener suppor…

…t in unsupporting environments.
  • Loading branch information...
1 parent 94748ed commit 1bba387bc87e023ce587310cb025bfb7123b0142 Scott Jehl committed Aug 3, 2012
Showing with 43 additions and 0 deletions.
  1. +43 −0 matchMedia.addListener.js
View
43 matchMedia.addListener.js
@@ -0,0 +1,43 @@
+/*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */
+(function(){
+ // monkeypatch unsupported addListener/removeListener with polling
+ if( !window.matchMedia( "" ).addListener ){
+ var oldMM = window.matchMedia;
+
+ window.matchMedia = function( q ){
+ var ret = oldMM( q ),
+ listeners = [],
+ last = false,
+ timer,
+ check = function(){
+ var list = oldMM( q );
+ if( list.matches && !last ){
+ for( var i =0, il = listeners.length; i< il; i++ ){
+ listeners[ i ].call( ret, list );
+ }
+ }
+ last = list.matches;
+ };
+
+ ret.addListener = function( cb ){
+ listeners.push( cb );
+ if( !timer ){
+ timer = setInterval( check, 1000 );
+ }
+ };
+
+ ret.removeListener = function( cb ){
+ for( var i =0, il = listeners.length; i< il; i++ ){
+ if( listeners[ i ] === cb ){
+ listeners.splice( i, 1 );
+ }
+ }
+ if( !listeners.length && timer ){
+ clearInterval( timer );
+ }
+ };
+
+ return ret;
+ };
+ }
+}());

0 comments on commit 1bba387

Please sign in to comment.
Something went wrong with that request. Please try again.