0

我想通过 Backbone.js 模型概念找到使用以下 JSON(信号值)的最佳方法:

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

到目前为止,我只看到 Backbone.Collections 可用于没有级别列表属性(例如:频率)的对象,如下所示:

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

2 回答 2

1

您可以使 items 数组成为自己的集合。

这是一些示例代码

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;
于 2012-08-09T14:48:47.477 回答
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();

});
于 2012-08-09T15:11:25.207 回答