将集合结果添加到视图和模板

Adding collection retsults to view and template

我正在使用 backbone 连接到第三方 api。我正在取回数据,但我很难弄清楚如何显示数据。

API returns 一个包含视频记录数组的对象。我可以在我的浏览器控制台中看到该对象,但我不知道如何通过 backbone.

在 html 模板中显示

这是我的代码:

           var RecordingCollection = Backbone.Collection.extend({
               url: '/api/camtasia',
               parse: function (resp) {
                 return JSON.parse(resp);
               },
           });

           var recordingCollection = new RecordingCollection();

           return Backbone.View.extend({
            className: 'camtasiaRender',
            template: _.template(tmpl, null, { variable: 'ctx' }),

            render: function () {
                recordingCollection.fetch();
                console.log('recordings: ', recordingCollection);           
                this.$el.html(this.template, recordingCollection);
                return this;
            }
    });
});

这是显示其中有数据的控制台屏幕截图:

recordings:  
child {
    length: 0,
     models: Array[0],
     _byId: Object,
     models: Array[0]
        0: Backbone.Model
            Attributes: Object
            attributes: Object
            odata.metadata: "http://SOM_camsite/Api/v1/$metadata#ApiKeys"
            value: Array[10]
            0: Object1: Object
            2: Object
            3: Object
            4: Object
            5: Object
            6: Object
            7: Object
            8: Object
            9: Object
            length: 10

您应该在 Collection 的 sync 事件上呈现您的视图。

您的观点应该在 initialize 上收听 collection:

var RecordingsView = Backbone.View.extend({
    initialize: function() {
        this.listenTo(this.collection, 'sync', this.render);
    }
});

var recordings = new RecordingCollection();
var recordingsView = new RecordingsView({collection: recordings});

recordings.fetch();