在View中使用REST调用渲染Backbone Collection

时间:2014-04-10 20:26:05

标签: javascript rest backbone.js

我试图让一个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>

1 个答案:

答案 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);