简体   繁体   中英

Meteor call template method from another method

I want to call a method within a method for clientside but I don't know how to handle it, i've tried by calling like myFunction() and this.myFunction() but it is not working... This is my code

Template.decision.rendered = function () {
    if ($(".active").length == 0) {
        var random = Math.floor(Math.random() * 1000);
        var $items = $(".item");
        $items.eq(random % $items.length).addClass("active");
    }
    $.each($(".item"), function (index, value) {
        if (Session.get($(this).attr('id'))) {
            this.showResults(value.option);
        }
    });
};
Template.decision.showResults = function($option) {
    $('#result').html('Option ' + $option + ' is voted');
};

As you can see I want to call showResults for each item inside rendered callback...

Found it using Template.decision.showResults(); silly me.

I think that a better way depending on what you are trying to do would be either to use a Session variable or a Meteor Method:

Session Variable.

Template.decision.created = function() {
  Session.setDefault('showResults', false);
}

Template.decision.rendered = function() {
  // [...]

  $.each($(".item"), function (index, value) {
    if (Session.get($(this).attr('id'))) {
      Session.set('showResults', true);
    }
  });
}

Template.decision.showResults = function() {
   return Session.get('showResults');
}

// in your template
<template name="decision">
  {{#if showResults}}
    <p>Here is the results.</p>
  {{/if}}
</template>

Meteor Method.

// On the client.
Template.decision.rendered = function() {
  // [...]

  $.each($(".item"), function (index, value) {
    if (Session.get($(this).attr('id'))) {
      Meteor.call('showResults', function(error, result) {
        if (!error and result === true) {
          $('.class').hide()  // It is here that you modify the DOM element according to the server response and your needs.
        }
      });
    }
  });
}

// Server-side method
// But, if you want it to react like a stub, put it inside your lib folder.
Meteor.methods({
  showResults: function() {
    // do your thing
    result = true; // let's say everything works as expected on server-side, we return true
    return result;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM