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