javascript – 在Ember.js App中显示在线和离线(例如飞机)模式

前端之家收集整理的这篇文章主要介绍了javascript – 在Ember.js App中显示在线和离线(例如飞机)模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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>

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>

Note: I’ve used the js lib 07002 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) {
    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并脱机,查看模板中的状态如何更改,返回联机状态再次看到它.

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

希望它有帮助

原文链接:https://www.f2er.com/js/151499.html

猜你在找的JavaScript相关文章