主干集合提取数据,但不设置模型

Backbone collection fetches data, but doesn't set models

本文关键字:设置 模型 数据 集合 提取      更新时间:2023-09-26

我正在尝试从本地 API 填充我的 Backbone 集合并更改视图以显示数据。我的集合中的 fetch() 调用似乎成功,并获取数据,但 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 

这向我表明 fetch 调用正在获取数据,但它没有用它填充模型。谁能告诉我我在这里做错了什么?

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

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

并请考虑@Pappa提出的建议。

您正在对 BookList 集合调用 fetch 两次,一次是在初始化时,另一次是在初始化 BookListView 时。在实例化集合时填充集合本身被认为是不好的做法。您还将在其初始化调用中呈现视图两次,一次是为了响应"reset"事件,然后您也直接调用它。

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