主干集合的模型对象结构不正确

Backbone collection's models-object incorrect structure?

本文关键字:对象 结构 不正确 模型 集合      更新时间:2023-09-26

我相信,在这个过程中,我的 Backbone 集合没有正确存储它们的模型。我还使用主干分页来分页集合,我的主干应用程序基于 https://github.com/alessioalex/ClientManager 和一些主干教程。

基本上,据我了解,骨干集合应该有一个模型属性,即:

Object
  models: Array
    0: Object
      model
      model, etc

但我的似乎有这样的结构:

Object
  models: Array
    0: Object
      attributes: Object
        tasks: Array (from my server JSON response)
        total_match, etc (other variables for pagination)

因此,在我的模板中,我总是必须使用任务[0].each,而不仅仅是任务。

这也意味着,当将模型添加到集合时,它们不会添加到任务中的模型数组中,而是 Backbone 在模型中创建了另一个数组,使其变为:

Object
  models: Array
    0: Object
      attributes: Object
        tasks: Array (from my server JSON response)
        total_match, etc (other variables for pagination)
    1: Object
      (new model attributes)

这意味着我的模板代码,搜索任务[0]没有选择它。这也意味着对于我的集合,我不能使用 collection.get(id),它不返回任何内容 - 即使使用正确的 ID 并为模型指定了 IDAttribute 也是如此。

我有点难倒。

您的服务器似乎返回了嵌套在 JSON 响应中的tasks数组。 为了让 Backbone 知道如何正确解析 JSON,您需要覆盖 parse() 方法并告诉它使用 tasks 数组作为模型的源。

var MyModel = Backbone.Model.extend({});    
var MyCollection = Backbone.Collection.extend({
        model: MyModel,
        parse: function(response) {
           //tell Backbone to turn each element in 'tasks' into an instance of MyModel
           return response.tasks;  
        }
});