Search code examples
javascriptbackbone.jsbackbone-views

Adding collection retsults to view and template


I am using backbone to connect to a 3rd-party api. I am getting data back, but I'm having a hard time figuring out how to display the data.

The API returns an object that contains an array of video recordings. I can see the object in my browser console, but I can't figure out how to display in an html template via backbone.

Here is my code:

           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;
            }
    });
});

Here is a screenshot of the console that shows there is data in there:

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

Solution

  • You should render your view on sync event from Collection.

    Your view should listen to collection on initialize:

    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();