2013-05-10 48 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