0

My application has an auto-complete text element and when the selected item is chosen, there is a RESTful ajax call that queries a secondary system which returns a detailed version of the selected object along with an array. It looks something like this:

{
    "state": "GA",
    "name": "Some Name",
    "status": "Appointed",
    "address2": "",
    "phone": "555-555-5555",
    "postalCode": 7777777,
    "agents": [
        {
            "middleName": "Rhett",
            "firstName": "Elmer",
            "id": 123456,
            "email": "",
            "documentDeliveryOptions": [],
            "lastName": "Butler Jr"
        },
        {
            "middleName": "Alvin",
            "firstName": "Frank",
            "id": 9123456,
            "email": "",
            "documentDeliveryOptions": [],
            "lastName": "Brown Jr"
        }
    ]
}

Originally, I made the query using a Collection, but I'm not really returning a Collection. I'm returning a single object with a nested Collection. So my question is, what is the appropriate Backbone way to query for this object and then populate a SELECT element with the nested Collection of agents?

Outside of backbone, I'd make a simple $.getJSON() call and then parse the response. I'm just not familiar enough with Backbone to understand what the best pattern is for the framework.

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • If I understand right, you want to retrieve the `agents` attribute of the Backbone Model and make a ` – Akos K Jul 21 '15 at 07:47

1 Answers1

0

One way to deal with it is by creating nested models & collections, I usually take this approach. One possible implementation can be :

var AgentsCollection = Backbone.Collection.extend({});

var SomeModel = Backbone.Model.extend({
  initialize: function(){
    this.agents = new AgentsCollection;  
  }
});
...
changeAutoSelect: function(){   //called when an item in auto-select is selected
  (new SomeModel()).fetch().done(function(){
    //render select here
  }
}
...

References :

http://backbonejs.org/#FAQ-nested

Can we omit parentheses when creating an object using the "new" operator?

Community
  • 1
  • 1
coding_idiot
  • 13,526
  • 10
  • 65
  • 116