2016-05-21 67 views
0

enter image description here接入骨幹示範

大家好數組,

如何訪問此數組中的骨幹中的每個對象的字段(僱員&位置)?

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" 

謝謝!

回答

0

在這裏,您可以從您的端點獲得Backbone Collection模型。比你可以訪問所有的模型。

Collection Models:原始訪問集合內部模型的JavaScript數組。通常你想使用getat,或Underscore 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>

+0

運行完美。但是,我如何將它綁定到視圖?謝謝。 –

+0

您可以創建Backbone視圖並傳遞集合:'var view = new MyView({collection:new DataCollection()}); '。在'MyView'中,你聲明'sync'事件,使'fetch'和操作集合顯示在視圖模板中 –