【问题标题】:MeteorJS: How to get id to load from collectionMeteorJS:如何获取要从集合中加载的 id
【发布时间】:2018-01-06 04:19:19
【问题描述】:

我正在尝试加载一个数组(带有简单文本),并尝试在调用它时将其加载到模板上。如何从该特定项目中获取 ID 以获取我存储在其中的数组?

HTML 模板:

<template name="commentMarker">
    <div id="viewMarker">
        <h3 id="markerTitle">{{markerName}}</h3>
        <h6 id="markerCategory">{{markerCategory}}</h6>
        <br>
        <fieldset>
            <legend>Description</legend>
            <p>{{markerDescription}}</p>
        </fieldset>
        <form id="commentForm"> 
            <fieldset>
                <legend>Comments</legend>
                <input type="text" id="markerId" name="idForComment" value={{markerId}}>
                <textarea rows="3" cols="19" name="comment" id="commentArea" placeholder="Insert your comment here..."></textarea>
                {{#each comments}}
                    <p id="oneComment">{{this}}</p>
                {{/each}}
            </fieldset>
            <input type="submit" value="Comment" class="commentButton">
            <input type="submit" value="Close" class="exitButton">
        </form>
    </div>
</template>

JS:

Template.commentMarker.helpers({
comments(){
        alert(template.find("#markerId").value);
        if(commentArray.length===0) return;
        else return commentArray;
    }});

这是我将评论插入集合项目的地方,它工作正常

Template.commentMarker.events({
    'click .commentButton': function(e, template){
        e.preventDefault();
        var id = template.find("#markerId").value;
        var comment = template.find("#commentArea").value;
    Points.update(id, { $push: { comments: comment }});
        commentArray = Points.findOne(id).comments;
        template.find("#commentArea").value = ' ';
    }

我尝试将commentArray 作为全局变量,现在仍然如此。但是我不知道如何从该特定项目中获取 Id,我什至将它的 Id(带有隐藏显示)放入表单中以实际插入评论。但这并不能帮助我显示 cmets,因为我似乎无法在 Template.helpers 中找到该字段 ...

【问题讨论】:

    标签: html meteor


    【解决方案1】:

    不完全确定您要做什么。这几乎就像您在更新到集合后立即显示 cmets。看起来您完全是在本地而不是在线集合上执行此操作。

    但是,将其存储为会话将起作用...或响应式 var。可能不是最好的解决方案。基本上将commentArray = Points.findOne(id).comments;替换为:

    Session.set('comments', Points.findOne(id).comments)
    

    然后在助手中将其取出:

    let commentArray = Session.get('comments')
    

    始终将其用于敏感数据并不安全。还可以尝试捕获 findOne(id).cmets,因为如果碰巧找不到它会产生错误。

    注意:如果要使用 Meteor.Methods,则不能使用 Session。您必须返回 id 并在您的助手中找到它。

    【讨论】:

    • 是的,试过了,效果很好。谢谢 :) 关键是返回一个简单文本(cmets)数组,然后在触发标记(在地图上)时加载模板中的所有内容。在我找到这样做的“安全方式”之前,这会很好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 2020-07-13
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2017-12-09
    相关资源
    最近更新 更多