在Ember.js应用程序中显示在线和离线(例如飞机)模式

Display online and offline (e.g. airplane) mode in an Ember.js App

本文关键字:飞机 模式 离线 js Ember 应用程序 在线 显示      更新时间:2023-09-26

余烬应用程序可以知道网络状态吗?如果是:如果应用程序可以访问互联网,我如何获取信息?我想根据网络可访问性来切换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>

app.js

App = Ember.Application.create();

简体:

既然你要求一个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>

注意:我已经使用了js库heyoffline.js,因为它是IMO周围最好的一个。我还覆盖了显示模态窗口的函数(lib显示默认情况下离线发生时的模态窗口,但因为我们要通过ember应用程序控制它,所以不需要),要让它回来,只需删除原型覆盖。

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({});

要测试它是否有效,请加载jsbin并脱机,查看模板中的Status如何变化,再回到在线查看它的变化。

有了这个设置,你应该得到浏览器的在线/离线状态烬的方式,享受:)

希望有所帮助

使用HTML5,您可以检查navigator.onLine布尔状态。

if (navigator.onLine) {
    // Online
} else {
    // Offline
}

如果需要监听下线或上线,可以处理windowofflineonline事件。请注意,在IE中,事件是为document.body引发的,而不是window

引用:

  • https://developer.mozilla.org/en-US/docs/DOM/window.navigator.onLine
  • https://developer.mozilla.org/en-US/docs/Online_and_offline_events