在Meteor JS中单击按钮时显示集合中的数据

时间:2015-09-15 16:02:14

标签: javascript jquery mongodb meteor meteor-helper

我有两个集FoodCategory(_id,Category)FoodInfo (_id,Category,Cat_ID,FootItem,Cost)

当用户点击FootItem显示Cost的按钮时,我想显示CategoryFoodCategory,我已经显示按钮显示类别,但没有绕过概念如何在单击按钮时从集合中检索数据。

文件1. ManageFoodItem.html

<template name="manageFoodItems">
   <button type="button" class="btn btn-primary " id="updateNewItemBtn">Update Item</button>
   <div class="updateItemPanel">        
      {{#each catDisplay}}
          {{> manageFoodUpdateItemSection}}
      {{/each}}     
   </div>
</template>
<template name="manageFoodUpdateItemSection">
   <a class="btn btn-default expandCategory" href="#" role="button">{{Category}}</a>   
   <div id="categoryFoodItem">
      <!--This is where I want to display FootItem when Foot Category button with Class expandCategory is clicked-->
      {{FoodItem}}                                              
   </div>
</template>

ManageFoodItem.js

Template.manageFoodItems.helpers({
    catDisplay: function() {
        return FoodCategory.find({});
    }
});

ManageFoodUpdateItemSection.js

此模板位于文件ManageFootItem.html

Template.manageFoodUpdateItemSection.events({
    'click .expandCategory': function(evt, tmpl) {
        evt.preventDefault();
        var clikedFoodCatId = this._id;
        alert(clikedFoodCatId);
        Session.set("curFoodCatID", clikedFoodCatId);
        return FoodInfo.find({
            Cat_ID: clikedFoodCatId
        });
    }

});

Template.manageFoodUpdateItemSection.helpers({
    footItemDisplay: function() {
        var curFoodId = Session.set("curFoodCatID");
        curFoodId = "jZyBxkfEAHJrdaKJ6";
    }
});
help函数中的

footItemDisplay可以检索集合中的数据(如果我使用的话),但是当我点击显示{{Category}}的按钮时我希望数据显示。

1 个答案:

答案 0 :(得分:2)

您可以使用Session来存储_id的当前文档FoodCategory,并进一步对点击事件作出反应。例如:

if (Meteor.isClient) {
    Template.manageFoodUpdateItemSection.helpers({
        currentFoodItem: function() {
            return Session.get('catId') == this._id;
        },
        FoodInfo: function() {
            return FoodInfo.find({"Cat_ID": Session.get('catId')});
        }
    });
    Template.manageFoodUpdateItemSection.events({
        'click .expandCategory': function() {
            Session.set('catId', this._id);
        }
    });
}
<template name="manageFoodUpdateItemSection">
    <a class="btn btn-default expandCategory" href="#" role="button">{{Category}}</a>
    {{#if currentFoodItem}}
        <div id="categoryFoodItem">
            {{#each FoodInfo}}
                {{FoodItem}}
            {{/each}}
        </div>
    {{/if}}
</template>