从RESTful服务查看骨干数据

时间:2014-05-14 18:15:50

标签: javascript python web-services backbone.js flask

我正在尝试查看从服务导入的集合,在客户端使用骨干,并使用python / flask作为服务。当我发出GET请求时,我得到以下数据:

{"entries": [{"Title": "my title 1", "Description": "My desc 1", "Info": "Info 1", "ids": 1}, {"Title": "my title 2", "Description": "My desc 2", "Info": "Info 2", "ids": 2}]}

但即使我使用fetch,这些条目也没有显示在我的页面上。这是我的ListView代码:

var app = app || {};

app.ContactListView = Backbone.View.extend({
 el: '#contacts',

initialize: function () {

    this.collection = new app.ContactList();
this.collection.fetch({reset: true});
    this.render();
this.listenTo( this.collection, 'reset', this.render );
},


render: function () {
    this.collection.each(function( item ){
    this.renderContact( item );
}, this );
},

renderContact: function ( item ) {
    var contactView = new app.ContactView({
        model: item
    });
    this.$('#ContactTable').append( contactView.render().el );
}
});

可能是什么原因?

1 个答案:

答案 0 :(得分:1)

原因是因为您的集合期待一系列模型作为其响应,但您的服务正在条目下返回数组。来自documentation

  每当收集模型时,Backbone都会调用

解析   由服务器返回,在fetch中。该函数是原始的   响应对象,并应返回模型属性数组   添加到集合中。

要解决此问题,您只需覆盖parse方法即可返回模型数组。

例如:

app.ContactList = Backbone.Collection.extend({
      //...
     parse: function (response) {
         return response.entries;
     } 
})