.fetch()集合backbone.js不起作用

时间:2017-01-18 10:29:15

标签: javascript backbone.js backbone-collections backbone-local-storage

我想调用API URL来获取数据,并将其传递给视图,但在使用fetch属性时遇到错误:

Uncaught TypeError: Cannot read property 'localStorage' of undefined  
    at G.d.Backbone.sync (backbone.localStorage-min.js:8)  
    at G.d.fetch (backbone-min.js:23)  
    at G.d.initialize (backbone:120)  
    at G.d.g.Collection (backbone-min.js:18)  
    at new G.d (backbone-min.js:38)  
    at backbone:137

代码:



var app = {};
app.postCollection = Backbone.Collection.extend({

  url: 'https://jsonplaceholder.typicode.com/comments',
  initialize: function(){
    this.fetch({
      success: this.fetchSuccess,
      error: this.fetchError
    });
  },

  fetchSuccess: function (collection, response) {
    console.log('Collection fetch success', response.data);
    /*console.log('Collection models: ', this.models);*/
  },

  fetchError: function (collection, response) {
    throw new Error(" fetch error");
  }

});

try {
  app.postcollection = new app.postCollection();
}
catch (e) {
  console.log(e.message);
}

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
    		  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
    		  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
    		  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您使用的是旧版本的localStorage。更新到新版本,例如$ git reset --hard HEAD $ git branch backup # backup your branch for safety $ git pull origin master -s recursive -X theirs # accept remote master changes if conflicts Or, $ git pull origin master -s recursive -X ours # accept local changes if conflicts

此外,您需要在集合https://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.16/backbone.localStorage.js

上指定localStorage属性

Working JSFiddle