[更新]
我才意识到这里有什么问题。
Meteor.call 正在调用异步函数,例如 ajax 调用。所以Meteor.call('getPhoto') 会返回 undefined,结果只能在回调中获取
Meteor.call('getPhoto',function(err,result){console.log(result)});
考虑到这一点,您需要想出一种方法来捕获回调中的结果。一种解决方案是使用ReactiveVariable:
您首先需要$ meteor add reactive-var
Template.comment.created = function (){
var $this = this;
$this.photo = new ReactiveVar("loading");
Meteor.call('getPhoto', function (err, result) {
if (err) console.log(err);
$this.photo.set(result);
});
}
现在定义你的助手来获取值;
//this is optional
Template.comment.helpers({
photo: function(){
return Template.instance().photo.get();
}
});
另一种解决方案是使用Session:
//everything here is in the client
Meteor.call('getPhoto', function(error, result){
Session.set('thePhoto', result);
});
// use reactive Session variable in helper
Template.comment.helpers({
photo: function(){
return Session.get('thePhoto');
}
});
使用Session 的问题在于您正在设置一个全局变量,如果您有很多 cmets,并且每条评论都需要有一张独特的照片,Session 可能不是最好的方法。
您在声明助手时调用了函数Meteor.call。
Template.comment.helpers({
photo: Meteor.call('getPhoto', function(error, result) {console.log(result);return result})
});
所以你正在做的相当于:
var a = Meteor.call('getPhoto', function(error, result) {console.log(result);return result})
Template.comment.helpers({
photo: a //a is just a value
});
要使.helpers 正常工作,您应该为photo 分配一个函数。
Template.comment.helpers({
photo: function(){
var r;
Meteor.call('getPhoto', function(error, result) {r = result});
return r;
}
});
在底层,每个助手都会启动一个新的 Tracker.autorun。当它的反应性依赖发生变化时,助手会重新运行。助手依赖于他们的数据上下文、传递的参数和其他在执行期间访问的反应数据源。 -来自 Meteor Doc
.helpers 应该被调用,因为您要使用.helpers 的原因是在您的视图中启用reactivity。因此,.helpers 内部的内容必须是函数。
如果你还是不明白我的意思,这里是简化的例子:
var a = function(){ console.log("hey"); return 1}
var b = a();
var c = a;
b(); //this would run into an error saying that b is a not a function
c(); //this would console.log "hey"