依赖选择框流星

时间:2012-11-10 15:31:57

标签: meteor

我正试图围绕流星依赖关系和反应变量。 我有两个选择框。一个列出一个类别(水果,蔬菜,家禽等),第二个列出子类别(苹果,梨,葡萄等)。

我想在用户更改类别下拉列表时显示并填充子类别下拉列表。

我知道我可以观看Template.action_form.events = {'change #category'} ......但我不确定从这里采取什么步骤。一个想法(hack)是将所有子类别输出到多维数组并使用jquery来管理它。我不得不认为有更聪明的方法可以用流星做到这一点。

对于类别下拉列表我有这样的事情:

Template.action_form.category = function(id){
    return Category.find();
}

我不确定如何为子类别设置模板...现在我有了这个(不工作)

Template.action_form.subcategory = function(parent){
  if (document.getElementById(parent)){
      category = document.getElementById(parent).value;
      return Subcategories.find({category_id:parent}); 
  }
}

HTML /模板如下所示:

<template name="action_form">
    <select id="category" class="action-selects">
        {{#each category _id}}
        <option value="{{_id}}">{{name}}</option>
        {{/each}}
    </select>
    <select id="subcategory" class="action-selects">
        {{#each subcategory "category"}}
        <option value="{{_id}}">{{name}}</option>
        {{/each}}
    </select>
<template>

感谢您提供的任何指示。

1 个答案:

答案 0 :(得分:2)

如果你想使用meteor的整个反应性魔法,你可以设置一个Session变量,如果第一个选择改变。

Template.action_form.events = {
  'change #category': function(evt) {
     Session.set("selected_category", evt.currentTarget.value);
  }
}

您的Subcategories订阅会将所选类别作为参数传递到服务器发布方法。

// Client
Meteor.autosubscribe(function () {
  Meteor.subscribe("subcategories",Session.get("selected_category"));
}

// Server
Meteor.publish("subcategories", function(selectedCategory) {
  Subcategories.find({category_id: selectedCategory})  
});

子类别的模板如果找到则显示所有Subcategories

Template.action_form.subcategory = function(parent){
  Subcategories.find();
};

当然,您可以一次发布所有子类别(不知道您将有多少子类别)并过滤客户端中的子类别,而不是在订阅/发布方法中。

Template.action_form.subcategory = function(parent){
  Subcategories.find({category_id: Session.get("selected_category")});
};
相关问题