Question

I am trying to retrieve my model from a JSON that has arrays with sub arrays and I am getting crazy. The objects get populated but not with the Models expected. I manage to make those from first level work fine, but the trick doesn't seem to work for the 2 level. Any alternative way of doing this would be much appreciated. I am quite new with Backbone.

Code:

(function () {
  "use strict";
      APP.Models.User = Backbone.Model.extend({
        initialize: function() {
            var listener = function() { console.log('myUser Updated'); };
            this.bind("changes", listener);
        },        
        url: myurl,
        parse: function(response){
            response.result.contents = new APP.Collections.Library(response.result.contents);
            response.result.contents.forEach(function(content) {        
                content.set('contacts', APP.Collections.Contacts(content.get('contacts')));
            });                 
            return response.result;
        }                           
      });
}());

JSON:

{
    "status": 1,
    "result": {
        "contents": [
            {
                "contentId": "1",
                "title": "test 1",
                "contacts": [
                    {
                        "nickName": "contact 1",
                        "phoneNumber": "11111"
                    },
                    {
                        "nickName": "contact 2",
                        "phoneNumber": "22222"
                    },
                    {
                        "nickName": "contact 3",
                        "phoneNumber": "33333"
                    }
                ]
            },
            {
                "contentId": "2",
                "title": "test 2",
                "contacts": [
                    {
                        "nickName": "Contact 4",
                        "phoneNumber": "44444"
                    },
                    {
                        "nickName": "Contact 5",
                        "phoneNumber": "5555"
                    }
                ]
            }
        ]
    }
}
Was it helpful?

Solution

Ok... silly me, I was missing the keyword new before APP.Collection.Contacts(). In any case it doesn't seem like the most elegant way. Any suggestion for an improvement is much appreciated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top