1

我正在一个集合中工作,该集合包含一个带有“自身”集合的模型。例如:

[{
     id: 1
     name: "John",
     children: [
         {
              id: 32
              name: "Peter",
              children: []
         },
         {
              id: 54
              name: "Mary",
              children: [
                  {
                      id:12,
                      name: "Kevin"
                  }
         ]
         },
     ]
}]

假设我想通过其 ID 获取 Kevin“用户”。但我所拥有的只是“第一个收藏”。我怎样才能做到这一点??关于在集合中设置用户?另一件事:有可能从他那里得到所有凯文的“父母”吗?像玛丽和约翰?

有没有人遇到过这样的问题?

多谢

4

2 回答 2

0

下划线(这是一个 Backbone 依赖项,所以你已经拥有它)非常适合这种事情;如果你使用它的“map”函数(Backbone 作为 Collection 上的一个方法提供)和它的 find 函数,你可以执行以下操作:

findPersonInPeopleCollection: function(nameWeAreLookingFor) {
    function findChildren(person) {
        if (!person.children) return [person];
        var children = _.map(person.children, function(child) {
            foundPeople.push(findChildren(child);
        })
        return _.flatten(children);
    }
    var allPeople = _.flatten(myCollectionOfPeople.map(findChildren));
    return _(allPeople).find(function(person) {
        return person.get('name') == nameWeAreLookingFor;
    }
}

如果您最初想存储父母,您可以向“Person”模型类的初始化函数添加逻辑,例如。

var Person = Backbone.Model.extend({
    initialize: function() {
        _.each(this.get('children'), function(child) {
            child.parent = this;
        }, this);
    }
 });

您也可以通过覆盖集合的 add 方法或向其中添加一个在添加人员后触发的事件处理程序来执行类似的操作。

于 2012-10-27T00:37:56.453 回答
0

好吧,我在 User's Collection 上创建了一个递归函数,似乎暂时解决了这个问题(最好的一点是我可以使用它来检索“深层”模型并对其进行更改。)。类似的东西(如果有人有任何建议,请自由发表意见):

findUserById: function(id) {
        var self = new Backbone.Collection(this.toJSON());

        return thisCollection(id, this);

        function thisCollection(id, collection, array) {
            var innerSelf = collection || this;
            var thisArray = array || [];
            for(var i = innerSelf.models.length; i--;) {
                if(innerSelf.models[i].get('id') == id) {
                    return [innerSelf.models[i]].concat([thisArray]);
                }else {
                    if(innerSelf.models[i].get('children').length > 0) {
                        thisArray.push(innerSelf.models[i]);
                        return thisCollection(id, innerSelf.models[i].get('children'), thisArray);
                    }else {
                        innerSelf.remove(innerSelf.models[i]);
                        return thisCollection(id, self, []);
                    }   

                }
            }
        }

    }

基本上我返回一个包含 2 个项目的数组。第一个是我要查找的记录,第二个是包含该用户父母的数组。

于 2012-10-30T11:32:59.093 回答