流星类别和子类别选择菜单

时间:2015-10-04 06:34:23

标签: javascript recursion meteor meteor-blaze spacebars

我是Meteor的新手,但对这个框架有了一些公平的了解。我正在创建一个应用程序,我必须在其中构建类别管理模块,我正在使用类别集合,在文档中我的值是这样的

{
_id:
name:
parentID:

.....
}

我已经尝试了很少的东西让它递归,但没有做到,我需要的是一个包含所有类别及其子项的下拉菜单。像这样:

http://blog.digibali.com/wp-content/uploads/2011/03/menutree2.jpg

如果有人在这个问题上可以提供帮助,我将不胜感激:

现在我正在做的是把我带到只有2个级别,我的意思是Top Parent和Sub Child,我想要无限级别,我知道它可能通过递归函数,但无法找到方法< / p>

模板:

<template name="categoryselect">

<select id="category" name="category" class="category">
<option value="">--Select--</option>
{{#each get_categories}}
<option value="{{_id}}">{{name}}</option>
{{#each get_sub_categories}}
{{> subcategoryselect}}
{{/each}}
{{/each}}

</select>

</template>


<template name="subcategoryselect">
<option value="{{_id}}">--{{name}}</option>
</template>

模板助手:

Template.categoryselect.helpers({
'get_categories': function(){
return Categories.find({parentID:''});

},

'get_sub_categories': function(){
return Categories.find({parentID:this._id});
}

});

1 个答案:

答案 0 :(得分:2)

这是一个经过测试的解决方案:

<强> HTML

<template name="categoryselect">
  <select id="category" name="category" class="category">
    <option value="">--Select--</option>
    {{#each get_categories}}
      <option value="{{_id}}">{{name}}</option>
    {{/each}}
  </select>
</template>

<强> JS

Template.categoryselect.helpers({
  get_categories: function() {
    var results = [];

    var mapChildren = function(category, level) {
      // add the appropriate number of dashes before each name
      var prefix = Array(2 * level).join('--');
      results.push({_id: category._id, name: prefix + category.name});

      // repeat for each child category
      var children = Categories.find({parentID: category._id}).fetch();
      _.each(children, function(c) {
        // make sure to increment the level for the correct prefix
        mapChildren(c, level + 1);
      });
    };

    // map each of the root categories - I'm unsure if the parent
    // selector is correct or if it should be {parentId: {$exists: false}}
    _.each(Categories.find({parentID: ''}).fetch(), function(c) {
      mapChildren(c, 0);
    });

    // results should be an array of objects like {_id: String, name: String}
    return results;
  }
});
相关问题