在"add"事件上运行方法的Backbone Collection获取:";TypeErr
Backbone Collection running a method on the `add` event getting: "TypeError: obj[implementation] is not a function"
我想要的目标是让控制台记录每个帖子的标题(从我的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'));
},
相关文章:
- 铬:“;未捕获的语法错误:意外的标记:"
- 可以设置“;文件名"发生错误时显示的内联脚本标记的
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 使用“+="操作人员
- //而不是在src=“”上使用http://"属性
- "未捕获的语法错误:意外的标记}"
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- "实例范围”;TypeScript类的getter/setter
- Javascript复选框函数:;缺少:在属性id之后"
- "“;变量未引用正确的对象
- "日期“;AJAX请求返回的类型值未定义
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- "工具提示"jQuery插件坏了
- "锻造;React中的表达式
- 图像可以从源<img src=""/>.TEXT可以在没有javascript的情况下从外部
- 如何提取“;href"最近列表项中的属性值
- CKEditor如何允许href="javascript:void(0)"在小部件中
- "this.collection.each不是函数;.应该'它不是简单地说“;每个”;