简体   繁体   English

来自另一种方法的Meteor调用模板方法

[英]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 我想在客户端的方法中调用一个方法,但我不知道如何处理它,我已经尝试通过调用myFunction()this.myFunction()但它不工作...这是我的代码

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... 正如你所看到的,我想为rendered回调中的每个项目调用showResults ...

Found it using Template.decision.showResults(); 使用Template.decision.showResults();找到它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变量或Meteor方法:

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;
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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