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

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

Patricia Arquette
Release: 2024-10-29 02:36:29
Original
725 people have browsed it

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>
    Copy after login
  2. Call the Method:

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

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

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template