2013-10-20 102 views
12

我试图从本地API填充我的Backbone集合并更改视图以显示数据。我的集合中的fetch()调用似乎成功了,并抓取数据,但获取操作不会更新集合中的模型。骨干集合获取数据,但不设置模型

这是我已经得到了我的模型和收集:

var Book = Backbone.Model.extend(); 

var BookList = Backbone.Collection.extend({ 

    model: Book, 
    url: 'http://local5/api/books', 

    initialize: function(){ 
     this.fetch({ 
      success: this.fetchSuccess, 
      error: this.fetchError 
     }); 
    }, 

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

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

}); 

,我已经做了我的看法是这样的:

var BookView = Backbone.View.extend({ 

    tagname: 'li', 

    initialize: function(){ 
     _.bindAll(this, 'render'); 
     this.model.bind('change', this.render); 
    }, 

    render: function(){ 
     this.$el.html(this.model.get('author') + ': ' + this.model.get('title')); 
     return this; 
    } 

}); 

var BookListView = Backbone.View.extend({ 

    el: $('body'), 

    initialize: function(){ 
     _.bindAll(this, 'render'); 

     this.collection = new BookList(); 
     this.collection.bind('reset', this.render) 
     this.collection.fetch(); 

     this.render(); 
    }, 

    render: function(){ 
     console.log('BookListView.render()'); 
     var self = this; 
     this.$el.append('<ul></ul>'); 
     _(this.collection.models).each(function(item){ 
      console.log('model: ', item) 
      self.appendItem(item); 
     }, this); 
    } 

}); 

var listView = new BookListView(); 

和我的API返回的JSON数据是这样的:

[ 
    { 
     "id": "1", 
     "title": "Ice Station Zebra", 
     "author": "Alistair MacLaine" 
    }, 
    { 
     "id": "2", 
     "title": "The Spy Who Came In From The Cold", 
     "author": "John le Carré" 
    } 
] 

当我运行这段代码我得到这个在控制台:

BookListView.render() app.js:67 
Collection fetch success Array[5] 
Collection models: undefined 

它向我表明提取调用正在获取数据,但它没有用它填充模型。任何人都可以告诉我我在这里做错了什么?

回答

12

您的fetchSuccess函数应该有collection.models而不是this.models

console.log('Collection models: ', collection.models); 

请考虑@Pappa提供的建议。

+0

非常感谢user10,那就是答案!我仍然在找到自己的方式,并没有意识到“this”在fetchSuccess中具有全局作用域 - 我仍然不是100%确定为什么,但是当我将“this”绑定到fetchSuccess初始化它拥有的集合时集合的范围。 –

+0

'fetchSuccess'是Backbone.sync调用的回调函数,由Backbone.js在全局范围内执行。 – user10

+0

Ohhhh所以这就是为什么!感谢user10。 –

8

您在您的BookList集合中调用两次fetch,一次是初始化时,另一次是您的BookListView初始化时。在实例化的时刻收集一个集合被认为是不好的做法。您还在初始化调用中呈现您的视图两次,一次是为了响应“重置”事件,然后您也直接调用它。

我建议从您的BookList集合中完全删除初始化函数,并删除对this.render();的调用。在您的BookListView的初始化调用结束时。

+1

谢谢帕帕,我会给你非常有用的建议! –

+0

如果一个视图有一个初始化方法,它会自动调用this.render()? –

+1

@AlexMills不,您必须手动调用渲染功能。 – Kevin