win*_*yer 10 javascript ember.js
Ember应用程序可以了解网络状态吗?如果是:如果应用程序可以访问互联网,我如何获取信息?我想根据网络可访问性切换GUI元素.
的index.html
<script type="text/x-handlebars">
Status:
{{#if isOffline}}
Offline
{{else}}
Online
{{/if}}
<hr>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<h2>Hello World</h2>
</script>
Run Code Online (Sandbox Code Playgroud)
app.js
App = Ember.Application.create();
Run Code Online (Sandbox Code Playgroud)
int*_*xel 18
简短:
既然你要求使用ember应用程序,我会花一些时间来提供一个可接受的答案.这是工作的jsbin.
长:
我在这里添加一些代码,对于完整的代码,请查看提供的jsbin.
的index.html
<script type="text/x-handlebars">
Status:
{{#if App.isOffline}}
<span class="offline">Offline</span>
{{else}}
<span class="online">Online</span>
{{/if}}
<hr>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<h2>Hello World</h2>
</script>
Run Code Online (Sandbox Code Playgroud)
注意:我使用过js lib heyoffline.js,因为它是IMO最好的之一.我还覆盖了显示模态窗口的函数(当脱机发生时,lib show默认为模态窗口,但是因为我们将通过我们的ember应用程序来控制它,所以不需要它),只需删除原型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) {
return this.options.onOnline.call(this);
}
};
Heyoffline.prototype.hideMessage = function(event) {
if (event) {
event.preventDefault();
}
//this.destroyElements();
if (this.options.onOffline) {
return this.options.onOffline.call(this);
}
};
//ember app
var 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 instantiation
this.set('service', new Heyoffline());
// hook into the two important events
this.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({});
Run Code Online (Sandbox Code Playgroud)
要测试它是否有效,请加载jsbin并离线,查看模板中的状态如何更改,然后重新联机以再次更改.
有了这个设置,您应该获得浏览器的在线/离线状态,享受:)
希望能帮助到你
使用HTML5,您可以检查navigator.onLine布尔状态.
if (navigator.onLine) {
// Online
} else {
// Offline
}
Run Code Online (Sandbox Code Playgroud)
如果你需要听离线或在线,你可以处理offline和online事件window.请注意,在IE中,事件是针对的document.body,而不是window.
参考文献: