1
votes

I have a fairly novice question and am hoping someone can help me.

I have the following code in which subscribe/publish is not working:

if (Meteor.isServer) {

  Meteor.publish('items', function () {
     return Items.find({});
   });

}


if (Meteor.isClient) {
  Meteor.subscribe("items");

}

In my template:

<template name="items">

  <div class="ui segment">
   <div class="ui relaxed list">
     {{#each item in items}}
     <div class="item">
        <img class="ui avatar image" src="http://placehold.it/20x20">
           <div class="content">
             <a class="header">{{item.text}} 

           </div>
           <button class="delete">&times;</button>
      </div>
      {{/each}}
   </div>
  </div>

</template>

But nothing gets output. However when I add:

 Template.items.helpers({
      items: function () {
        return Items.find({});
      }
    });

I do see the list properly. Why is this so? Also I am clearly confused as to why someone would want to use subscribe/publish along with the template helpers.

2

2 Answers

1
votes

You must subscribe() using the same name as used in the publish(). In your case (pay attention to 'items'):

/server:

Meteor.publish('items', function () {
   return Items.find({});
});

/client:

if (Meteor.isClient) {
  Meteor.subscribe('items');
}

The publish/subscribe link is telling meteor to send all docs in the 'Items' collection to minimongo on the client. Now, the purpose of the template helper is to tell meteor that you want to reactively update the template any time a document changes in Items.

A good reference on the subject: https://www.discovermeteor.com/blog/understanding-meteor-publications-and-subscriptions/

1
votes

I suggest you read Data flow from the database to the UI: Three layers of Meteor

You are creating a publication labeled: items. Then you are subscribing to a publication labeled deals. This will not work as the labels must match for the subscription to work.

If adding that template helper then shows the data in the UI, you must have the autopublish package in your app. It will be autopublish, not your pub/sub, that is sending the client the data the client puts in it's mini-mongo Items collection.

So pub/sub gets the data from the server to the client, but doesn't display it. That is why you need the template helper, to get the data from the client's mini-mongo collection into the format the templates require.