2017-08-31 59 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)) 

或多或少...