在"add"事件上运行方法的Backbone Collection获取:";TypeErr

Backbone Collection running a method on the `add` event getting: "TypeError: obj[implementation] is not a function"

本文关键字:quot Collection Backbone 获取 TypeErr 运行 add 事件 方法      更新时间:2023-09-26

我想要的目标是让控制台记录每个帖子的标题(从我的API获取(。然而,我似乎做了一些错误的事情,特别是我在this.listenTo(PostCollection, 'add', this.render);行上得到了Uncaught TypeError: obj[implementation] is not a function——我想监听对PostCollection的任何添加,并激发事件以从API获取所有对象。以下是错误堆栈:

Uncaught TypeError: obj[implementation] is not a function
_.each.Events.(anonymous function) @ backbone.js:225
Backbone.View.extend.initialize @ test.js:61
Backbone.View @ backbone.js:1001
child @ backbone.js:1566
(anonymous function) @ test.js:70
(anonymous function) @ test.js:72

API回应:https://gist.github.com/anonymous/c270f9ca9befa054ecef

我的主干代码:

(function ($) {
    var Post = Backbone.Model.extend({
        url: 'http://api.xxx.com/wp-json/posts',
        defaults: {
            id: null,
            status: '',
            title: ''
        }
    });
    var PostCollection = Backbone.Collection.extend({
        model: Post,
        url: 'http://api.xxx.com/wp-json/posts',
        sync: function (method, model, options) {
            return Backbone.sync(method, model, options);
        },
        parse: function (response) {
            if (response) {
                var listSource = [];
                _.each(response, function (element, index, list) {

                    listSource.push(new Post({
                        id: element.id,
                        title: element.title,
                        status: element.status
                    }));

                });
                return listSource;
            } else {
                alert('Error...');
                return [];
            }
        }

    });

    var AppView = Backbone.View.extend({
        el: '#app',

        render: function () {
            console.log(this.model.get('title'));
        },
        initialize: function () {

            this.listenTo(PostCollection, 'add', this.render);
            PostCollection.fetch();
        }
    });

    new AppView();
})(jQuery);

我的HTML:

<!doctype html>
<html lang="en" data-framework="backbonejs">
    <head>
        <meta charset="utf-8">
        <title>FOO</title>
    </head>
    <body>
        <div id="app"></div>

        <script src="node_modules/jquery/dist/jquery.js"></script>
        <script src="node_modules/underscore/underscore.js"></script>
        <script src="node_modules/backbone/backbone.js"></script>
        <script src="js/test.js"></script>
    </body>
</html>

您需要实例化您的集合。您正试图在一个类上listenTo和Fetch,而您应该在该类的一个实例上这样做。

 this.collection = new PostCollection();
 this.listenTo(this.collection, 'add', this.render);
 this.collection.fetch();

我无法检查您的代码,因为我没有端点,但看起来您在render函数中的console.log也不起作用。首先,您没有定义模型。我想你想打印刚刚添加的帖子的标题。这样做的一种方法是:

 render: function () {
     console.log(this.collection.last().get('title'));
 },