Ben Wong Ben Wong - 1 year ago 92
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: ""
urlRoot: ""

var locationModel = new DataModel();
locationModel.urlRoot = ""

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


Answer Source

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: ''

var locationCollection = new DataCollection();
locationCollection.once('sync', function(r) {
    console.log('Collection length: ', r.length);
<script src=""></script>
<script src=""></script>
<script src=""></script>