2017-08-31 45 views
0

我已經使用Backbone.js構建了一個Web應用程序,並且它有很多打電話給REST風格的服務,它的功能就像一個魅力。服務人員塊backbonejs?

我試着添加一個ServiceWorker來緩存所有以前的調用,以便它們可以脫機使用。

我實際得到的是,我是第一次做的呼籲,死亡與此錯誤:

Failed to load resource: net::ERR_FAILED

但是在頁面重載,我得到它的緩存數據

我的服務人員獲取:

self.addEventListener('fetch', function(e) { 
// e.respondWidth Responds to the fetch event 
e.respondWith(

    // Check in cache for the request being made 
    caches.match(e.request) 
     .then(function(response) { 

      // If the request is in the cache 
      if (response) { 
       console.log("[ServiceWorker] Found in Cache", e.request.url, response); 
       // Return the cached version 
       return response; 
      } 

      // If the request is NOT in the cache, fetch and cache 

      var requestClone = e.request.clone(); 
      fetch(requestClone) 
       .then(function(response) { 

        if (!response) { 
         console.log("[ServiceWorker] No response from fetch ") 
         return response; 
        } 

        var responseClone = response.clone(); 

        // Open the cache 
        caches.open(cacheName).then(function(cache) { 

         // Put the fetched response in the cache 
         cache.put(e.request, responseClone); 
         console.log('[ServiceWorker] New Data Cached', e.request.url); 

         // Return the response 
         return response; 

        }); // end caches.open 
        console.log("Response is.. ?", response) 
        return response; 

       }) 
       .catch(function(err) { 
        console.log('[ServiceWorker] Error Fetching & Caching New Data', err); 
       }); 


     }) // end caches.match(e.request) 
); // end e.respondWith 
}); 

編輯: 我不認爲有必要的ny Backbone.js網絡應用代碼。 我使用Backbone.js模型和集合中的fetch方法。 電話像 https://jsonplaceholder.typicode.com/posts/1https://jsonplaceholder.typicode.com/posts/2

將重播顯示在第一次此錯誤。刷新頁面後,我確實沒有請求這些信息。全部來自緩存。 和所有其他的要求,我仍然沒有做,會留下錯誤

+0

請包括[MCVE。 –

+0

我編輯:我不認爲有任何Backbone.js網絡應用程序代碼的需要。我使用Backbone.js模型和集合中的獲取方法。像https://jsonplaceholder.typicode這樣的調用。com/posts/1和https://jsonplaceholder.typicode.com/posts/2 將在第一次播放時顯示此錯誤。刷新頁面後,我確實沒有請求這些信息。全部來自緩存。和所有其他請求,我仍然沒有做,將保持錯誤 – Gugu

回答

0

我看到的唯一的問題是,當請求不在緩存中,然後你做一個fetch,但你不知道回報的結果fetch到封閉的then處理程序。您需要添加一個return,讓您有:

return fetch(requestClone) 
      .then(function(response) { 

return聲明爲fetch提供您then處理程序中的數據沒有將得到以其他方式轉讓了鏈。


我也看到你不回由caches.open(cacheName).then...提供的承諾。這可能如果你想解耦保存響應緩存中的結果返回鏈上,但至少我會發表評論說,這就是我在這裏做的,而不是離開它讀者可以確定return聲明是否意外丟失,或者是故意排除的。

0

我解決了它後搜索更多。 Backbone.js的我的用來做網絡應用的觀點:

this.listenTo(this.collection,"reset",this.render); 
this.listenTo(this.collection,"add",this.addCollectionItem); 
this.listenTo(this.collection,"error", this.errorRender); 

,而我的服務工人返回承諾。

我不得不改變我的一些代碼,我的Web應用程序意見是這樣的:

this.collection.fetch({},{reset:true}) 
    .then(_.bind(this.render, this)) 
    .fail(_.bind(this.errorRender,this)) 

或多或少...