我的Meteor js应用程序中有一个非常有趣的问题:当我在模板的onCreated方法中调用meteor方法时,该方法调用的回调有时会立即返回undefined作为结果。事实证明,这是因为模板是在运行流星方法模拟时创建的。
两个问题:
Meteor.setTimeout
不允许这样做?)一些代码:
// My Template (Not my real code, just to demonstrate)
Template.saying.onCreated(() => {
var tmpl = Template.instance();
tmpl.saying = new ReactiveVar();
Meteor.call('getSaying', (err, saying) => {
// If called inside of a simulation, saying is null
tmpl.saying.set(saying);
});
});
// Assume that the above template is used in an {{each}} block
// and somewhere in my code I call this
Items.insert({});
// Because Items.insert wraps a meteor method which also runs as a
// simulation on the client, then the Template.saying.onCreated
// callback will be called in the context of an active simulation,
// which means that 'getSaying' method call will return immediately
// with undefined as the result.
答案 0 :(得分:0)
避免模拟的两种可能性:
使用isClient。运行模拟时,它将评估为真
if (Meteor.isClient) {
// on the client, the return value of a stub is ignored
return;
}