Meteor.call(..) 会导致刷新页面

Meteor.call(...) causes refresh the page

本文关键字:刷新 call Meteor      更新时间:2023-09-26

我正在使用Meteor开发一个非常简单的投票应用程序。

voteapp.meteor.com

单击投票按钮(选择选项后显示)后,页面将刷新。

点击事件:

    Template.poll.events({
    "click input.inc": function (event) {
        // Prevent default browser form submit
        event.preventDefault();
        Meteor.call('voteForAnswer', Session.get("selectedanswer"), function (error, result) {
            if (error) {
                Session.set("voteError", error.reason);
            }
            else {
                Session.set("voteError", null);
                Session.set("selectedpoll", result);
            }
        });
    }
});

流星呼叫功能:

'voteForAnswer': function (id, vote) {
    var answer = Answers.findOne(id);
    var poll = Polls.findOne(answer.poll);
    if (poll && answer) {
        Answers.update(answer, { $inc: { score: 1 } }, function (error) {
            if (error) {
                throw new Meteor.Error(411, "Answer could not be updated.");
            }
        });
        Polls.update(poll, { $inc: { sum: 1 }, $set: { lastActivity: new Date() } }, function (error) {
            if (error) {
                throw new Meteor.Error(411, "Poll could not be updated. " + poll.name);
            }
        });
        poll = Polls.findOne(poll._id);
        var answers = Answers.find({ poll: poll._id }).fetch();
        answers.forEach(function (ans) {
            ans.score && Answers.update(ans, { $set: { percent: Math.round((parseInt(ans.score) / parseInt(poll.sum)) * 100) } });
        });
        poll.answers = Answers.find({ poll: poll._id }, { sort: { score: -1 } }).fetch();
    }
    return poll;
}

也:

if (Meteor.isClient) {
Meteor.subscribe("polls");
Meteor.subscribe("answerswers");

和:

if (Meteor.isServer) {
    Meteor.publish("polls", function () {
        return Polls.find();
    });
    Meteor.publish("answerswers", function () {
        return Answers.find();
    });
}

我发现了问题。我将 Meteor.methods(...) 移到 if (Meteor.isServer) { ... } 块。现已修复。