Home > Article > Web Front-end > Can You Call Meteor Methods Directly from Template Helpers?
Using Meteor Methods in Template Helpers
In Meteor, template helpers provide reactive data to the template. A common question arises: can we access Meteor methods directly from within these helpers?
Consider the following code:
<code class="javascrip">// server-side method Meteor.methods({ // viewTest method to return a string viewTest: function(str) { return str; } }); // client-side helper Template.helloWorld.helpers({ // attempt to call 'viewTest' method txt: function() { return Meteor.call('viewTest', 'Hello World.'); } });</code>
When attempting to render the template, the helper function throws an error, indicating that the method does not exist. This is because Meteor attempts to render the template before registering the method on the client.
Alternative Implementation
There is an updated approach in Meteor 0.9.3.1 that addresses this issue:
<code class="javascript">// client-side template Template.helloWorld.helpers({ txt: function() { return Template.instance().myAsyncValue.get(); } }); // client-side 'created' callback Template.helloWorld.created = function() { // create a ReactiveVar instance and attach it to the template this.myAsyncValue = new ReactiveVar("Waiting for response from server..."); // call the 'getAsyncValue' method and update the ReactiveVar when the callback fires Meteor.call('getAsyncValue', (err, asyncValue) => { if (err) console.log(err); else this.myAsyncValue.set(asyncValue); }); };</code>
This solution uses ReactiveVars, which are reactive data sources tied to template instances. By storing the method result in a ReactiveVar and updating it in the callback, the helper can access the returned value reactively.
The above is the detailed content of Can You Call Meteor Methods Directly from Template Helpers?. For more information, please follow other related articles on the PHP Chinese website!