Javascript Meteor从另一个方法调用模板方法
我想在clientside的方法中调用一个方法,但我不知道如何处理它,我尝试过调用Javascript Meteor从另一个方法调用模板方法,javascript,jquery,methods,callback,meteor,Javascript,Jquery,Methods,Callback,Meteor,我想在clientside的方法中调用一个方法,但我不知道如何处理它,我尝试过调用myFunction()和this.myFunction(),但它不起作用。。。这是我的密码 Template.decision.rendered = function () { if ($(".active").length == 0) { var random = Math.floor(Math.random() * 1000); var $items = $(".ite
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');
};
如您所见,我想为
呈现的回调中的每个项目调用showResults
。使用Template.decision.showResults()找到它代码>愚蠢的我。我认为一个更好的方法是使用会话变量或Meteor方法,这取决于您尝试执行的操作:
会话变量。
但如果我想在showResults方法中编辑DOM元素呢?它在Meteor内部不起作用。方法,对吗?比如说Console.log(“投票”)
我想做$('#投票').html('voated')代码>您不能在Meteor.methods中编辑DOM元素(因为您是服务器端的,而jQuery仅在客户端可用),但这将在Meteor.call回调中起作用(因为代码是在客户端运行的)。您能给我举一个Meteor.call回调的示例来操作DOM元素吗?因为这是最终目的,我将用一个例子来更新我的问题。基本上就是我所问的,如何调用方法来操作DOM元素,我不想要任何复杂的东西,只是从一个方法中操作DOM。
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>
// 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;
}
});