Javascript Meteor模板帮助程序:{{keyname}}显示空白
comment.html:Javascript Meteor模板帮助程序:{{keyname}}显示空白,javascript,meteor,handlebars.js,meteor-blaze,Javascript,Meteor,Handlebars.js,Meteor Blaze,comment.html: <template name="comment"> <img src="{{photo}}"> //blank {{photo}} //blank </template> server.js: Meteor.methods({ getPhoto: function () { return Meteor.user().services.vk.photo; } }); 问题:
<template name="comment">
<img src="{{photo}}"> //blank
{{photo}} //blank
</template>
server.js:
Meteor.methods({
getPhoto: function () {
return Meteor.user().services.vk.photo;
}
});
问题:
console.log返回正确的值,但{photo}为空。
问题:为什么“照片”是空的?[更新]
我刚意识到这里有什么问题
Meteor.call
调用一个异步函数,就像ajax调用一样。因此,Meteor.call('getPhoto')
将返回未定义的,结果只能在回调中检索
Meteor.call('getPhoto',function(err,result){console.log(result)});
考虑到这一点,您需要想出一种在回调中捕获结果的方法。一种解决方案是使用:
您首先需要$meteor添加反应式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
的一点是,您正在设置一个全局变量,如果您有许多注释,并且每个注释都需要一张独特的照片,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
});
为了正常工作,您应该将一个函数指定给photo
Template.comment.helpers({
photo: function(){
var r;
Meteor.call('getPhoto', function(error, result) {r = result});
return r;
}
});
在引擎盖下,每个助手启动一个新的Tracker.autorun。当助手的反应依赖项更改时,将重新运行该助手。助手依赖于其数据上下文、传递的参数以及在执行期间访问的其他反应数据源-来自流星博士
.helpers
应该被调用,这正是您希望使用的原因。helpers
应该在您的视图中启用。因此,.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"
谢谢你的回答。我很抱歉修改了comment.js文件,但没有任何变化;(@bartezr有没有记录任何结果?这是否可能是由于您的
@bartezr中缺少“
”,我刚刚解决了问题;请稍等;@bartezr刚刚更新了我的帖子;经过测试;现在肯定可以用了。现在效果很好。谢谢您的帮助,很抱歉浪费了您的时间。
Template.comment.helpers({
photo: function(){
var r;
Meteor.call('getPhoto', function(error, result) {r = result});
return r;
}
});
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"