2012-08-09 41 views
0

我想找到使用下面的JSON(信號的值)throught Backbone.js的模型的概念的最佳方式:如何應對Backbone.js的與級別列表屬性集合

{ 
    frequency: "1/1", 
    items: [ 
     { 
      value: 1, 
      quality: 5 
     }, 
     { 
      value: 0.5, 
      quality: 5 
     } 
     ] 
} 

所以到目前爲止,我只看到物體可用Backbone.Collections無級列表屬性(例如:頻率),如下所示:

[ 
    { 
     value: 1, 
     quality: 5 
    }, 
    { 
     value: 0.5, 
     quality: 5 
    } 
] 

回答

0

可以使用骨幹型號爲每一個信號,然後組集合中的模型,並有「頻率」的集合屬性。像這樣:

var Model_Signal = Backbone.Model.extend({ 

    defaults: { 
     value: 0, 
     quality: 0 
    }, 

    initialize: function(){ 

     // Do some initializing. 
     // you'll probably want to set the 
     // model's defaults here. 

    } 

}); 


var Collection_Signals = Backbone.Collection.extend({ 

    frequency: null, 

    model: Model_Signal, 

    calculateFrequency: function(){ 

     // You'll probably want to do this every time you 
     // add a new signal to this collection. 

    } 

}); 

然後,您可以遍歷您的JSON對象,實例化新模型並將它們添加到集合中。

var jsonObject = { 
    frequency: "1/1", 
    items: [ 
    { 
     value: 1, 
     quality: 5 
    }, 
    { 
     value: 0.5, 
     quality: 5 
    } 
    ] 
}; 



// Instantiate the collection 
var signalCollection = new Collection_Signals(); 

_.each(jsonObject.items, function(item){ 

    var signalModel = new Model_Signal({value: item.value, quality: item.quality}); 
    signalCollection.add(signalModel); 
    signalCollection.calculateFrequency(); 

}); 
1

可以使項目陣列自己的收藏。

下面是一些示例代碼

SignalItem = Backbone.Model.extend({ 
    defaults: { 
    value: 0, 
    quantity: 0 
    } 
}); 

SignalItemCollection = Backbone.Collection.extend({ 
    model: SignalItem 
}); 

Signal = Backbone.Model.extend({ 
    initialize: function() { 
    // convert the items JSON array into a Backbone collection 
    this.get('items') = new SignalItemCollection(this.get('items')); 
    } 
}); 

var signal = new Signal({ 
    frequency: 1, 
    items: [ 
    { 
     value: 1, 
     quality: 5 
    }, { 
     value: 2, 
     quality: 3 
    } 
    ] 
}); 

signal.get('frequency') === 1; 
signal.get('items').models[0].get('quality') === 5; 
+0

感謝您的回覆!非常感謝 ! – 2012-08-09 15:05:58