在Backbone模型中访问数组

时间:2016-05-21 16:07:53

标签: javascript backbone.js

enter image description here

大家好,

如何访问Backbone中此阵列中每个对象的字段(Employees& Location)?

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"

谢谢!

1 个答案:

答案 0 :(得分:0)

在这里,您可以从终端获取Backbone Collection个模型。比您可以访问所有模型。

Collection Models:对集合内JavaScript模型数组的原始访问。通常,您希望使用getatUnderscore methods来访问模型对象,但有时需要直接引用该数组:



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>
&#13;
&#13;
&#13;