2013-05-10 41 views
9

Ember应用程序能够了解网络状态吗?如果是:如果应用程序可以访问互联网,我如何获取信息?我想根据网络可访问性切换GUI元素。在Ember.js应用程序中显示在线和离线(例如飞机)模式

的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(); 

回答

18

短:

既然你问了一个余烬应用我奉献一些时间来提供可接受的答案这里是工作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 LIB heyoffline.js,因为它是最好的一个海事组织左右。 我也覆盖了显示模式窗口的函数(lib显示默认情况下发生脱机时的模式窗口,但由于我们要通过我们的应用程序应用程序来控制它,所以不需要),只需将它删除原型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和离线去,看看状态模板的变化,回去网上看到它再次发生变化。

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

希望它可以帮助

+0

宾果!谢谢。 – wintermeyer 2013-05-21 07:45:06

+0

Gern geschehen(不客气):) – intuitivepixel 2013-05-21 07:45:37

4

有了HTML5,你可以检查navigator.onLine布尔状态。

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

如果你需要监听脱机或联机去,你可以处理的windowofflineonline事件。请注意,在IE中,事件发生的次数为document.body,而不是window

参考文献:

+0

我将如何实现在灰烬应用程序? – wintermeyer 2013-05-10 20:35:34

+0

@wintermeyer我真的不确定 - 我从来没有用过它。但是,无论何时您需要知道计算机是否联机,只需检查'navigator.onLine'值并根据该代码进行操作即可。 – Ian 2013-05-10 20:54:44

+0

@wintermeyer如果您可以使用Ember应用程序准确解释如何使用它,我可以尝试帮助。但看起来很简单 - 只需检查属性,或将侦听器绑定到检测脱机/在线的特定事件 – Ian 2013-05-17 16:38:03