Created
April 2, 2011 23:06
-
-
Save pifantastic/899992 to your computer and use it in GitHub Desktop.
A simple framework for managing device dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function(global) { | |
var env = { | |
_deps: {}, | |
_ready: function() {}, | |
_change: function() {}, | |
// Add dependencies. | |
deps: function() { | |
for (var x = 0, len = arguments.length; x < len; x++) { | |
this._deps[arguments[x]] = false; | |
} | |
return this; | |
}, | |
// Update the state of a dependency. | |
dep: function(dep, state) { | |
if (dep in this._deps) { | |
if (arguments.length === 1) { | |
return this._deps[dep]; | |
} else { | |
this._deps[dep] = !!state; | |
this._change(dep, !!state); | |
for (var dep in this._deps) { | |
if (!this._deps[dep]) { | |
return this; | |
} | |
} | |
this._ready(); | |
return this; | |
} | |
} | |
}, | |
// Supply a callback to execute when all dependencies | |
// have been fulfilled. | |
ready: function(cb) { | |
this._ready = cb; | |
return this; | |
}, | |
// Supply a callback to execute when the state | |
// of a dependency changes. | |
change: function(cb) { | |
this._change = cb; | |
return this; | |
} | |
}; | |
this.env = env; | |
})(this.exports || this); | |
// Set up environment dependencies | |
env.deps('location', 'socket'); | |
// Fire this callback when all dependencies are ready. | |
env.ready(function() { | |
alert("Location and connection established."); | |
}); | |
// Fire this callback when a dependency's state changes | |
env.change(function(dep, state) { | |
console.log(dep + ' is now ' + (state ? 'ready' : 'missing')); | |
}); | |
navigator.geolocation.watchPosition(function(pos) { | |
env.dep('location', pos.coords.accuracy < 100); | |
}); | |
var socket = new io.Socket('127.0.0.1', {port: 1337}); | |
socket.on('connect', function() { | |
env.dep('socket', true); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment