简体   繁体   English

如何在骨干.js中处理嵌套集合

[英]How to handle nested collection in backbone.js

I have a collection of models. 我有一些模型。 Some of these models might contain a nested collection of the same models. 其中一些模型可能包含相同模型的嵌套集合。 In my JSON this is set up as an array. 在我的JSON中,将其设置为数组。 The issue I was getting was that it was remaining as an array and not getting parsed into the collection of models I wanted it to be. 我遇到的问题是它仍然作为数组保留,而没有被解析为我想要的模型集合。 This was a problem because I was navigating through the data recursively and I wanted to be able to treat each model as a Backbone model and not just a plain old object. 这是一个问题,因为我递归地浏览数据,并且希望能够将每个模型都视为Backbone模型,而不仅仅是一个普通的旧对象。 I am calling collection of model , within same model . 我正在调用同一模型内的模型集合。 Initialize function:- 初始化功能:

function(response) {

       if (response.filters) {
             this.set('filters', new FilterCollection(response.filters));
       }
  }

If I read your question correctly, you are trying to convert the array to a proper collection in initialize . 如果我正确阅读了您的问题,则您正在尝试将数组转换为initialize的适当集合。 That's not the ideal place. 那不是理想的地方。 Assuming you load your data from the server with fetch , the conversion needs to happen in parse instead. 假设您使用fetch从服务器加载数据,则转换需要parse

The parse method is also the right choice if you pass the attributes to the constructor while creating the model. 如果在创建模型时将属性传递给构造函数,则parse方法也是正确的选择。 The attributes will be processed with parse by setting the option {parse: true} . 通过设置选项{parse: true}将使用parse处理属性。 You don't need additional code in initialize for that. 为此,您不需要其他代码即可进行initialize The example in the Backbone documentation illustrates the very thing you are trying to do. Backbone文档中的示例说明了您正在尝试做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM