我在 meteor 模板管理器中有这样一段代码:
"click #refuse": function() {
Meteor.call("removeUserFromEvent", this._id, Meteor.userId());
if (Template.instance().data.participants.length === Template.instance().data.orderedParticipants.length) {
Meteor.call("updateEventStatus", this._id, "ordered");
}
Router.go("/");
}
我想让 if(...){...}
内容在 Meteor.call(...)
回调中执行,例如
"click #refuse": function() {
Meteor.call("removeUserFromEvent", this._id, Meteor.userId(), function(){
if (Template.instance().data.participants.length === Template.instance().data.orderedParticipants.length) {
Meteor.call("updateEventStatus", this._id, "ordered");
}
});
Router.go("/");
}
但是,如果我尝试执行此操作,结果会发现回调 Template.instance()
内部返回 null
,并且我无法从模板获取数据。
如何将这些内容(我的意思是,获取一些当前状态参数并根据这些调用或不调用另一个方法)放入方法回调中?也许 Template.instance().data 是存储状态参数的错误位置? Template.instance.data 是否是响应式(Reactive)的?也许我应该以某种方式改变架构,以使此类功能能够驻留在回调中?
最佳答案
这是一个事件处理程序,事件处理程序函数接受事件和模板作为参数,如 'event target': function(event, template) {}
中所示,因此您的代码可以修改为:
"click #refuse": function(evt,tmp) {
// get and cache your template data context references;
var participants = tmp.data.participants;
var orderedParticipants = tmp.data.orderedParticipants;
// this._id is not reliable, you should use Blaze.getData() on the event target
var _id = Blaze.getData(event.currentTarget)._id;
var userId = Meteor.userId();
// make sure your callback function accepts error and result
Meteor.call("removeUserFromEvent", _id, userId, function(err,res) {
if (err) {/* handle error */}
if (res) {
if (participants.length === orderedParticipants.length) {
Meteor.call("updateEventStatus", _id, "ordered", function(err,res) {
if (err) {/* handle error */}
if (res) {
// perhaps you would like to redirect to home after successful operation only
Router.go("/");
}
});
}
}
});
}
PS:这里有太多回调,因此您可能需要研究 Promise 来简化此代码。
关于javascript - 从方法调用回调访问meteorTemplate.instance().data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36319769/