How to deal with Backbone.js Collections with level-list properties
-
25-06-2021 - |
Question
I would like to find the best way to use the following JSON (values of a signal) throught Backbone.js Model Concept :
{
frequency: "1/1",
items: [
{
value: 1,
quality: 5
},
{
value: 0.5,
quality: 5
}
]
}
So far I only see Backbone.Collections usable on objects without level-list properties (e.g :frequency) like the following :
[
{
value: 1,
quality: 5
},
{
value: 0.5,
quality: 5
}
]
Solution
You can use backbone models for each signal, then group the models in the collection and have a collection attribute of 'frequency'. Like so:
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.
}
});
Then you can loop through your JSON object, instantiate new models and add them to the collection.
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();
});
OTHER TIPS
You can make the items array its own collection.
Here's some example code
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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow