json Backbone 集合获取数据,但不设置模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19476317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:55:32  来源:igfitidea点击:

Backbone collection fetches data, but doesn't set models

javascriptjsonbackbone.jsbackbone-views

提问by And Finally

I'm trying to populate my Backbone collection from a local API and change the view to show the data. The fetch() call in my collection seems to succeed, and grabs the data, but the fetch operation doesn't update the models in the collection.

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

This is what I've got for my model and collection:

这是我的模型和收藏品:

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");
    }

});

and I've done my views like this:

我已经完成了这样的观点:

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();

and my API returns JSON data like this:

我的 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é"
    }
]

When I run this code I get this in the console:

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

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

which indicates to me that the fetch call is getting the data OK, but that it's not populating the models with it. Can anyone tell me what I'm doing wrong here?

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

采纳答案by user10

Your fetchSuccessfunction should have collection.modelsnot this.models.

你的fetchSuccess函数应该collection.models没有this.models

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

and please consider suggestions given by @Pappa.

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

回答by Pappa

You are calling fetch on your BookList collection twice, once when it is initialized and again when your BookListView is initialized. It's considered bad practice to have a collection populate itself at the moment it's instantiated. You're also rendering your view twice inside its initialize call, once in response to the 'reset' event and then you're also calling it directly.

您在 BookList 集合上调用 fetch 两次,一次是在初始化时,一次是在 BookListView 初始化时。在实例化的那一刻让集合自行填充被认为是不好的做法。你还在它的初始化调用中渲染你的视图两次,一次是为了响应 'reset' 事件,然后你也直接调用它。

I would suggest removing the initialize function completely from your BookList collection, and removing the call to this.render(); at the end of your BookListView's initialize call.

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