Display Online And Offline (e.g. Airplane) Mode In An Ember.js App
Solution 1:
The short:
Since you asked for an ember app I've dedicated some time to provide an acceptable answer. Here is the working jsbin.
The long:
I add here some of the code, for the complete code please look at the jsbin provided.
index.html
<scripttype="text/x-handlebars">
Status:
{{#if App.isOffline}}
<spanclass="offline">Offline</span>
{{else}}
<spanclass="online">Online</span>
{{/if}}
<hr>
{{outlet}}
</script><scripttype="text/x-handlebars"data-template-name="index"><h2>Hello World</h2></script>
Note: I've used the js lib heyoffline.js since it's one of the best around IMO. I've also overriden the functions that show a modal window (the lib show's per default a modal window when offline occurs, but since we are going to control it trough our ember app it's not needed), to get it back just remove the prototype overiddes.
app.js
// overrides to not show the default modal window, to get it back just remove this overrides
Heyoffline.prototype.showMessage = function() {
//this.createElements();if (this.options.onOnline) {
returnthis.options.onOnline.call(this);
}
};
Heyoffline.prototype.hideMessage = function(event) {
if (event) {
event.preventDefault();
}
//this.destroyElements();if (this.options.onOffline) {
returnthis.options.onOffline.call(this);
}
};
//ember appvar App = Ember.Application.create({
isOffline: false,
service: null,
ready: function(){
this.set('service', App.HeyOffline.create());
}
});
// Heyoffline wrapper
App.HeyOffline = Ember.Object.extend({
service: null,
init: function(){
// heyoffline instantiationthis.set('service', new Heyoffline());
// hook into the two important eventsthis.set('service.options.onOnline', this.offline);
this.set('service.options.onOffline', this.online);
},
online: function(){
App.set('isOffline', false);
console.log("online");
},
offline: function(){
App.set('isOffline', true);
console.log("offline");
}
});
App.ApplicationRoute = Ember.Route.extend({});
To test that it works, load the jsbin and go offline, see how the Status in the template changes, go back online to see it change again.
With this setup in place you should get the online/offline status of the browser the ember way, enjoy :)
Hope it helps
Solution 2:
With HTML5, you can check the navigator.onLine
boolean status.
if (navigator.onLine) {
// Online
} else {
// Offline
}
If you need to listen for going offline or online, you can handle the offline
and online
events of window
. Note that in IE, the event is raised for document.body
, not window
.
References:
Post a Comment for "Display Online And Offline (e.g. Airplane) Mode In An Ember.js App"