Im新骨干,试图从Wordpress json插件获取json并渲染成模板,但是当循环发布时,出现以下错误未捕获的ReferenceError:帖子未定义任何帮助赞赏。谢谢...Backbone.js未捕获引用错误
jQuery(function($) {
var Post = Backbone.Model.extend();
var Posts = Backbone.Collection.extend({
model: Post,
url: '/api/get_post/?json=get_recent_posts',
parse: function(resp) {
console.log("posts", resp);
return resp;
}
});
var listView = Backbone.View.extend({
el: '#content',
template: _.template($("#post-template").html()),
initialize: function() {
this.model.bind("reset", this.render, this);
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
var AppRouter = Backbone.Router.extend({
routes: {
"!/archive": "archive"
},
archive: function() {
this.postList = new Posts();
this.postListView = new listView({
model: this.postList
});
this.postList.fetch();
this.postListView.render();
}
});
var app = new AppRouter();
Backbone.history.start();
});
模板
<script id="post-template" type="text/template">
<ul>
<% _.each(posts, function(post) { %>
<li id="<%= post.id %>">
<a href="<%= post.url %>"><%= post.thumbnail %></a>
</li>
<% }); %>
</ul>
</script>
的Json
{
"status": "ok",
"count": 1,
"count_total": 1,
"pages": 1,
"posts": [{
"id": 4,
"type": "post",
"slug": "test-post",
"url": "http:\/\/localhost:8888\/2013\/04\/test-post\/",
"status": "publish",
"title": "Test Post",
"title_plain": "Test Post",
"content": "",
"excerpt": "",
"date": "2013-04-17 15:12:21",
"modified": "2013-04-19 14:13:00",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"comment_count": 0,
"comment_status": "closed",
"thumbnail": "http:\/\/localhost:8888\/wp-content\/uploads\/2013\/04\/test-image-150x150.jpg"
}]
}
该错误来自模板编译器。作为一个提示,在你的'render()'中做一个'console.log(this.model.toJSON())',看看打印出来的内容。另外,'this.postList'是一个集合,那么为什么你将它作为'model'传入呢? – Bojangles 2013-04-22 13:55:59
@Bojangles关于最后一部分,在Backbone中没有用于视图的'collection'键,所以如果你想创建一个“集合视图”,你仍然必须使用'model'键。这不是什么问题。 – Loamhoof 2013-04-22 13:57:00
@Loamhoof请在评论之前阅读[文档](http://backbonejs.org/#View-constructor)。从骨干文档:'有几个特殊的选项,如果通过,将直接附加到视图:模型,集合,el,id,className,tagName和属性。' – Bojangles 2013-04-22 14:00:12