Ben Wong Ben Wong - 6 months ago 14
Javascript Question

Access an Array in Backbone Model

enter image description here

Hi all,

How do I access the fields(Employees & Location) of each object in this array in Backbone?

var DataModel = Backbone.Model.extend({
// urlRoot: "https://corporate-dashboard.firebaseio.com/locations.json"
urlRoot: ""
});

var locationModel = new DataModel();
locationModel.urlRoot = "https://corporate-dashboard.firebaseio.com/locations.json"
locationModel.fetch()



console.log(locationModel.get("Location")); >> Got "undefined"
tried locationModel.get(0) and locationModel[0] >> got "undefined"


Thanks!

Answer

Here you can get a Backbone Collection of models out from you endpoint. Than you can access to all the models.

Collection Models: Raw access to the JavaScript array of models inside of the collection. Usually you'll want to use get, at, or the Underscore methods to access model objects, but occasionally a direct reference to the array is desired:

var DataCollection = Backbone.Collection.extend({
    url: 'https://corporate-dashboard.firebaseio.com/locations.json'
});

var locationCollection = new DataCollection();
locationCollection.once('sync', function(r) {
    console.log('Collection length: ', r.length);
    console.log(r.models[0]);
    console.log(r.models[0].get('Employees'));
    console.log(r.models[0].get('Location'));
});
locationCollection.fetch();
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>