Home  >  Article  >  Web Front-end  >  How to Call Meteor Methods from Template Helpers Using Reactive Variables?

How to Call Meteor Methods from Template Helpers Using Reactive Variables?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 02:36:29700browse

How to Call Meteor Methods from Template Helpers Using Reactive Variables?

Calling Meteor Methods from Template Helpers

In Meteor, template helpers provide a way to dynamically generate content for templates. One common requirement is to call server-side Meteor methods from within these helpers.

Meteor 0.9.3.1 introduced a new approach for this scenario:

Using Reactive Variables:

  1. Create a Reactive Variable:

    <code class="js">Template.helloWorld.created = function() {
      this.myAsyncValue = new ReactiveVar("Waiting for response from server...");
    }</code>
  2. Call the Method:

    <code class="js">Meteor.call('getAsyncValue', function(err, asyncValue) {
      if (err) {
        console.log(err);
      } else {
        this.myAsyncValue.set(asyncValue);
      }
    });</code>
  3. Use the Helper:

    <code class="js">Template.helloWorld.helpers({
      txt: function() {
        return this.myAsyncValue.get();
      }
    });</code>

In this approach, the reactive variable this.myAsyncValue is attached to the template instance. The helper function returns the value of this variable, which is updated when the method callback fires.

Note: This approach requires the reactive-var package to be installed:

$ meteor add reactive-var

The above is the detailed content of How to Call Meteor Methods from Template Helpers Using Reactive Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn