gpt4 book ai didi

javascript - Backbone Collection 在 `add` 事件上运行方法并获取 : "TypeError: obj[implementation] is not a function"

转载 作者:行者123 更新时间:2023-12-03 09:38:31 25 4
gpt4 key购买 nike

我期望的目标是让控制台记录每个帖子的标题(从我的 API 获取)。然而,我似乎做错了一些事情,特别是我在 this.listenTo(PostCollection, 'add', this.render); -- 我想监听 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>

最佳答案

您需要实例化您的集合。您正在尝试对类进行监听和获取,而您应该在类的实例上执行此操作。

 this.collection = new PostCollection();

this.listenTo(this.collection, 'add', this.render);

this.collection.fetch();

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

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

关于javascript - Backbone Collection 在 `add` 事件上运行方法并获取 : "TypeError: obj[implementation] is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31255466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com