2015-12-06 2 views
0

Я пытаюсь преобразовать приложение-учебник Meteor, простое дело, в форум. У меня есть список, который заполняется темами с кнопкой удаления и переключателем.Link MongoDB collection

Что я хочу сделать, это когда переключатель радио темы выбран, отобразите все связанные с ним комментарии. Я пытаюсь выполнить это, поставив topicId (первоначально taskId), используемый в учебнике, в новой коллекции под названием «Комментарии». Затем я запрашиваю комментарии для этой темы. Комментарии чаще всего копируются и вставляются в темы, поэтому атрибуты и функциональность этих двух элементов в основном одинаковы.

Я, прямо сейчас, не знаю, как добраться до topicId от моего Template.body.events. Если вы можете помочь мне связать эти два БД вместе, это будет очень полезно.

HTML:

<head> 
    <title>Forum</title> 
</head> 

<body> 

    <div class="login"> 
    {{> loginButtons}} 
    </div> 

<nav class="mainMenu"> 
    <ul> 
    <li><a href="home.html">Home</a></li> 
    <li><a href="forum.html">Forum</a></li> 
    <li><a href="about.html">About Us</a></li> 
    </ul> 
</nav> 

<div class="container"> 
    <header> 
     <h1>Forum</h1> 
    <h2>Post a topic</h2> 

    {{#if currentUser}} 
    <form class="new-topic"> 
     <input type="topicalContent" name="topicalContent" placeholder="Type to add new topics" /> 
    </form> 
    {{/if}} 
</header> 

    <table> 
    <td class="topicsCol"> 
     <h3>Topics</h3> 

     <ul class="topicsList"> 
     {{#each topics}} 
     {{> topic}} 
     {{/each}} 
     </ul> 
    </td> 
    <td class="commentsCol"> 
     <h3>Comments</h3> 

     <ul class="commentsList"> 
     {{#each comments}} 
     {{> comment}} 
     {{/each}} 
     </ul> 

     <input type="commentContent" name="commentContent" placeholder="Type to Comment" /> 
    </td> 
    </table> 
</div> 
</body> 

<template name="topic"> 
<li class="{{#if selected}}select{{/if}}"> 
<button class="delete">&times;</button> 

<span class="topicalContent">{{topicalContent}} -<strong>{{username}}</strong></span> 

<input type="radio" name="curTopic" value="{{curTopic}}" /> 
</li> 
</template> 

<template name="commentsList"> 
    <li class="comment"> 
    <button class="delete">&times;</button> 
    <span class="responseContent"> 
     <strong> 
     <!-- {{#if username === owner}} 
      <style="color:red;">OP 
     {{else}}--> 
      {{username}} 
     <!--{{/if}}--> 
     </strong>: {{responseContent}}</span> 
    </li> 
</template> 

JavaScript:

Topics = new Mongo.Collection("topics"); 
Comments = new Mongo.Collection("comments"); 


if(Meteor.isServer){ 
    Meteor.publish("topics", function(){ 
    return Topics.find({ 
     $or: [ 
     { owner: this.userId } 
     ] 
    }); 
    }); 

    Meteor.publish("comments", function(){ 
    return Comments.find({ 
     $or: [ 
     { parent: topicId }, 
     { owner: this.userId } 
     ] 
    }); 
    }); 
} 


if (Meteor.isClient) { 
    // This code only runs on the client 
    Meteor.subscribe("topics"); 
    Meteor.subscribe("comments"); 

    Template.body.helpers({ 
     topics: function() { 
     return Topics.find({}, {sort: {createdAt: -1}}); 
    }, 

    comments: function() { 
     return Comments.find({parent: {parent: topicId}}, {sort: {createdAt: -1}}); 
    } 
    }); 

    Template.body.events({ 
     "submit .new-topic": function (event) { 
      //Prevent default browser form submit 
      event.preventDefault(); 

      //Get value from form element 
      var topicalContent = event.target.topicalContent.value; 

     if (topicalContent == "") { 
     throw new Meteor.Error("Empty Input"); 
     } 

      //Insert a topic into the collection 
      Meteor.call("addTopic", topicalContent); 

      //Clear form 
      event.target.topicalContent.value = ""; 
    }, 

    "submit .commentContent": function (event) { 
     event.preventDefault(); 

     var commentContent = event.target.commentContent.value; 

     Meteor.call("addComment", this.topicId); 

     event.target.commentContent.value= ""; 
    } 
    }); 


    Template.topic.helpers({ 
    isOwner: function(){ 
     return this.owner === Meteor.userId(); 
    } 
    }); 

    Template.topic.events({ 
     "click .curTopic": function() { 
      //Show Comments of selected radio button 
     Meteor.call("showComments", this._id); 
    }, 

    "click .delete":function() { 
     Meteor.call("deleteTopic", this._id); 
    } 
    }); 

    Template.comment.helpers({ 
    isOwner: function(){ 
     return this.owner === Meteor.userId(); 
    } 
    }); 
    Template.comment.events({ 
    "click .delete":function() { 
     Meteor.call("deleteComment", this._id); 
    } 
    }); 

    Accounts.ui.config({ 
    passwordSignupFields: "USERNAME_ONLY" 
    }); 
} 

Meteor.methods({ 
    addTopic:function(topicalContent){ 
    if (!Meteor.userId()) { 
     throw new Meteor.Error("not-authorized"); 
    } 

    Topics.insert({ 
     topicalContent, 
     createdAt: new Date(), 
     owner: Meteor.userId(), 
     username: Meteor.user().username 
    }); 
    }, 
    deleteTopic:function(topicId) { 
    var topic = Topics.findOne(topicId); 
    if (topic.owner !== Meteor.userId()) { 
     throw new Meteor.Error("not-authorized"); 
    } 
    else { 
     Topics.remove(topicId); 
    } 
    }, 

    showComments:function (topicId) { 
    Comments.find({"parent":topicId}); 
    }, 
    addComment:function(commentContent, topicId){ 
    if (!Meteor.userId()) { 
     throw new Meteor.Error("not-authorized"); 
    } 

    Comments.insert({ 
     commentContent, 
     createdAt: new Date(), 
     owner: Meteor.userId(), 
     username: Meteor.user().username, 
     parent: topicId 
    }); 
    }, 
    deleteComment:function(commentId) { 
    var comment = Comments.findOne(commentId); 
    if (comment.owner !== Meteor.userId()) { 
     throw new Meteor.Error("not-authorized"); 
    } 
    else { 
     Comments.remove(commentId); 
    } 
    } 
}); 

ответ

0

Один из способов (и есть много), чтобы использовать переменные сессии для отслеживания текущей темы. В обработчике события: topic

Template.topic.events({ 
    "click .curTopic": function() { 
    Session.set('topicId',this._id); // set the Session variable 
    Meteor.call("showComments", this._id); 
}); 

Теперь везде вы ищете текущий topicId вы можете просто использовать Session.get('topicId');

+0

Но, кстати, есть множество других проблем в вашем коде за просто делится состоянием от переключателей. Как вы публикуете «Комментарии», например. Функция публикации будет нуждаться в 'topicId', и вам вообще не нужен этот метод. –