Skip to content

Instantly share code, notes, and snippets.

@falkolab
Last active February 7, 2016 02:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save falkolab/d7462a1cee3e93a4bf3e to your computer and use it in GitHub Desktop.
Save falkolab/d7462a1cee3e93a4bf3e to your computer and use it in GitHub Desktop.
Network state monitor for Titanium SDK
require('networkMonitor').init();
function anyAction() {
require('networkMonitor').run(function online() {
// cancel monitoring for single action after success online
require('networkMonitor').cancel(online);
hideNetworkNotification();
// your action code here
}, function() {
showNetworkNotification();
}, $)
}
function cleanup() {
networkMonitor.cancelAll($);
}
// Network Monitor
// Author: Andrey Tkachenko <falko.lab@gmail.com>
// Source: https://gist.github.com/falkolab/d7462a1cee3e93a4bf3e
_.extend(exports, Backbone.Events);
var initilaized = false;
function testOnline(evt) {
if (evt.online) {
exports.trigger('online');
}
}
exports.run = function(func, failure, context) {
if(typeof func !== 'function') throw "Can't run not function object.";
if(Ti.Network.online) {
func();
} else {
this.on('online', func, context);
_.isFunction(failure) && failure();
}
};
exports.cancel = function(func, context) {
this.off('online', func, context);
};
exports.cancelAll = function(context) {
this.off('online', null, context || null);
};
exports.init = function() {
!initilaized && Ti.Network.addEventListener("change", testOnline);
};
exports.cleanup = function() {
if(initilaized) {
Ti.Network.removeEventListener('change', testOnline);
this.off();
initilaized = false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment