我试图让一个Collection在Backbone View中呈现,但它不会填充HTML。它将在获取后控制日志,但不会在_.each中控制日志。有线索吗?我是Backbone的新手,正在寻找基于REST调用填充的帮助。它适用于硬数据(来自数组的内联条目),但似乎在REST上绊倒。
<script>
var featuredArticle = Backbone.Model.extend({
defaults: {
id: '',
headLine: '',
snippet: '',
fullStory: '',
location: '',
nsfw: '',
category: '',
relatedArticleIds: '',
hasVideoPlaceholder: '',
numberOfImages: ''
}
});
var featuredArticles = Backbone.Collection.extend({
model: featuredArticle,
url: 'http://myrestendpoint'
});
var articleView = Backbone.View.extend({
tagName: 'ul',
render: function () {
var that = this;
var getfeaturedArticles = new featuredArticles();
getfeaturedArticles.fetch();
console.log(getfeaturedArticles);
_.each(that.collection, function (value) {
console.log(value.headLine);
$(that.el).append('<li>' + value.headLine + '</li>');
})
return that;
}
});
var articles = new articleView({collection: featuredArticles});
$("body").append(articles.render().el);
</script>
答案 0 :(得分:1)
创建articleView实例时,需要传递集合实例而不是包含定义的变量。 因此改变:
var articles = new articleView({collection: featuredArticles});
到
var articles = new articleView({collection: new featuredArticles});
在articleView的render方法中,使用fetch集合。 变化:
var getfeaturedArticles = new featuredArticles();
getfeaturedArticles.fetch();
console.log(getfeaturedArticles);
到
this.collection.fetch();
console.log(this.collection);