【问题标题】:Meteor Category and Subcategory Select Menu流星类别和子类别选择菜单
【发布时间】:2016-01-01 01:19:01
【问题描述】:

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

{
_id:
name:
parentID:

.....
}

我尝试了一些使其递归的方法,但未能做到,我需要的是一个包含所有类别及其子类别的下拉列表。像这样:

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

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

现在我正在做的只是将我带到 2 个级别,我的意思是顶级父级和一个子级,我想要无限级别,我知道这可能通过递归函数实现,但无法找到方法

模板:

<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});
}

});

【问题讨论】:

    标签: javascript recursion meteor meteor-blaze spacebars


    【解决方案1】:

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

    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;
      }
    });
    

    【讨论】:

    • 嗨,大卫,这就是我要找的东西 :),谢谢你的帮助,顺便说一句,它也让我对 Underscore.JS 助手有了一些了解;)
    猜你喜欢
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多