Helper meteor caused by several moments of one template variable

Tweets = new Meteor.Collection('tweets'); if (Meteor.isClient) { Meteor.subscribe('tweets'); Template.Panel.helpers({ items: function() { var days_tweets = Tweets.find(); console.log(days_tweets.count()); return days_tweets; }); } if (Meteor.isServer) { Meteor.publish('tweets', function() { return Tweets.find({}, {limit: 1000}); }); 

Template:

 <body> <h1>This is a list of tweets</h1> {{> Panel}} </body> <template name="Panel"> <h2>A list of tweets sorted by size</h2> {{#each items}} <p>item</p> {{/each}} </template> 

And console output when loading the page:

 Tweet count: 0 Tweet count: 129 Tweet count: 272 Tweet count: 366 Tweet count: 457 Tweet count: 547 Tweet count: 672 Tweet count: 814 Tweet count: 941 Tweet count: 1000 

Thus, the auxiliary function is triggered 10 times when the page loads (the number of times changes). Can someone explain what is going on here? I can not find any reference to this, accept in situations where the helper is called from several {{}} in the template. Also any way to stop it? In the end, I need to process the tweets at a time before they are rendered.

+7
javascript meteor
source share
1 answer

When you search, a meteorite registers the dependency for this template helper in the collection you found. Because of this dependency, meteor will call the template helper for each modification to the collection.

If you have not signed up yet, there is no data on the client copy of your Mongo collection. Only when the subscription is called will the meteor arrive with data from the server.

Thus, the method is called several times because the subscription continues to insert new documents into your local copy of the mongo collection, causing new calls to the template helper.

The best template for solving any problems that may arise is to subscribe to the helper and use the ready method on the documentation subscription. Ready also responds, so when all the data is ready, it will be changed to true, and the assistant will be called again.

  Template.Panel.helpers({ items: function() { var ready = Meteor.subscribe('tweets').ready(); var days_tweets = Tweets.find(); return { data: days_tweets, ready: ready }; }); } 

The template itself:

 {{#with items}} {{#if ready}} {{#each data}} <p>item</p> {{/each}} {{else}} Show a spinner or whatever {{/if}} {{/with}} 
+7
source share

All Articles