[英]Meteor method callback loop, what am I doing wrong?
我已經看了一段時間了,我很確定它與無限回調循環有關。
我有一個方法從稱為Sessions的集合中返回一個整數。 這是我的方法:
Meteor.methods({
going: function(sessionsId) {
return Sessions.update(sessionsId, {$addToSet: {participants: Meteor.userId()}, $inc: {slots:-1}});
},
retract: function(sessionsId) {
return Sessions.update(sessionsId, {$pull: {participants: Meteor.userId()}, $inc: {slots:1}});
},
sessionFull: function(sessionsId) {
var session = Sessions.findOne({_id:sessionsId});
console.log("gets here");
return session.slots;
}
});
然后在我的客戶中,我有:
if (Meteor.isClient) {
Template.hello.sessions = function () {
return Sessions.find();
};
Template.session.this_info = function () {
return this._id;
};
Template.session.isGoing = function() {
var session = Sessions.find({_id:this._id, participants:Meteor.userId()}).count();
if (session > 0) return true;
else return false;
};
Template.session.sessionFull = function() {
if (this.slots === 0) return true;
else return false;
};
Template.session.slotsMethod = function () {
Meteor.call('sessionFull',this._id, function(error, slots) {
Session.set("slots",slots);
});
return Session.get("slots");
};
Template.session.events({
'click input.going' : function () {
//Sessions.update(this._id, {$inc: {slots: -1}});
Meteor.call('going', this._id, function(error, updated) {
if (error)
return alert(error.reason);
});
},
'click input.retract' : function () {
Meteor.call('retract', this._id, function(error, removed) {
if (error)
return alert(error.reason);
});
}
});
因此,我基本上有幾個按鈕可以增加或減少slot字段,並且我想有一種方法可以返回slot字段包含的內容。 這是我的模板:
{{#each sessions}}
{{> session}}
{{/each}}
<template name="session">
<br>
{{date_time}}, {{duration}}
{{#if isGoing}}
<input type="button" class="retract" value="not going/give slot" />
{{else}}
{{#if sessionFull}}
<h1>SORRY SESSION FULL</h1>
{{else}}
<input type="button" class="going" value="going/subract slot" />
{{/if}}
{{/if}}
{{participants}},{{sessionFull}},{{this_info}}
</template>
如果我嘗試將Template.session.slotsMethod添加到我的模板中(該模板調用sessionFull流星方法),則會出現一個無限循環,例如,它將為每個會話顯示一個快速變化的整數。
難道我做錯了什么?? 無法弄清楚,我認為它與回調/異步/同步有關,但不確定。
是的,由於Session
是反應性的,因此Template.session.slotsMethod
將導致無限循環。
這是發生了什么:
Template.session.slotsMethod
因為它依賴於Session.get("slots")
。 Template.session.slotsMethod
本身也正在更新Session.get("slots")
的值,因此該過程將重新開始。 不確定何時要運行Template.session.slotsMethod
,但是您可能希望將其分解為兩部分,例如:
Template.session.getSlots = function () {
return Session.get("slots");
};
和
Meteor.call('sessionFull',this._id, function(error, slots) {
Session.set("slots",slots);
});
需要去哪里/何時需要進行sessionFull
檢查,也許在Template.session.rendered
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.