-
-
Save JamesEggers1/1904283 to your computer and use it in GitHub Desktop.
var OrientationManager = (function () { | |
"use strict"; | |
var supportsOrientationChange = window.hasOwnProperty("onorientationchange") | |
, orientationEvent = supportsOrientationChange ? "orientationchange" : "resize" | |
, currentOrientation = window.orientation || 0 | |
, currentWidth = window.outerWidth; | |
function orientationChanged(callBack) { | |
var newWidth = window.outerWidth | |
, newOrientation = window.orientation || (newWidth !== currentWidth) ? 1 : 0; | |
// only change orientation and call provided callback if necessary | |
if (newOrientation !== currentOrientation) { | |
currentOrientation = newOrientation; | |
currentWidth = newWidth; | |
if (callBack) { callBack(); } | |
} | |
} | |
// exports | |
return { | |
supportsOrientationChange: supportsOrientationChange | |
, orientation: currentOrientation | |
, orientationEvent: orientationEvent | |
, orientationChanged: orientationChanged | |
}; | |
} ()); | |
// jQuery binding usecase | |
$(function($){ | |
$(window).on(orientationEvent, function (){OrientationManager.orientationChanged(myCallback);}); | |
}); |
I don't think code will run as is. Line 32 tries to use the orientationEvent
variable but it is outside of the closure that that variable is declared in. I think it should instead use OrientationManager.orientationEvent
.
Looks good. Simple, I like it. I have a few suggestions:
-
Make the
OrientationManager.orientationChanged()
event support multiple callbacks. -
When the
OrientationManager.orientationChanged()
event fires the callback, either pass in theOrientationManager
as the contextthis
(i.e.callBack.apply(OrientationManager)
) or pass theOrientationManager
, or thenewOrientation
as an argument to thecallBack()
.I think this would make it slightly easier for the consumer since they won't have to turn around and call
OrientationManager.currentOrientation
in their callback function.
Hmm. Question. Is there a reason you don't set window.orientation
, if this is meant as a polyfill?
I created a repo under orientation-change-polyfill.
🍺 Feel free to contribute.
This script/polyfill also assumes 2 things about the page - html5 doctype and the viewport constrained.