Search code examples
javascriptbackbone.jsbackbone-views

backbone collection to view to template


I'm connecting to a 3rd-party API that returns an object which contains an array.

I'm trying to get that into a backbone collection, and then pipe that out to a view.

I tried a number of things, the most recent being something simple like this:

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

       var myCollection = new MyCollection();
       myCollection.fetch();

       return Backbone.View.extend({
           template: _.template(tmpl),

       render: function() {           
           this.$el.html(this.template({
                coll: myCollection.toJSON()
            }));
            return this;
       }

This just give me [Object Object] in my template.

If I write it out to the console, I just see:

YourCollection

[Object]
     yourdata.metadata: "www.xyz.edu/"
     value: Array[3]
        0: Object
           Id: "000"
           Name: "Name0"
           IsValid: True
        1: Object
           ID: "111"
           Name: "name1"
           IsValid: True
        3: Object
           ID: "222"
           Name: "name2"
           IsValid: True

It would be nice if I could get each array element into it's own model, but I'm not sure how to do that.

Thanks!


Solution

  • Seems like you need to filter actual collection inside your parse method:

    function (resp) {
      return JSON.parse(resp).value;
    }