gpt4 book ai didi

javascript - meteor 模板助手 : {{keyname}} showing blank

转载 作者:行者123 更新时间:2023-11-30 16:57:15 24 4
gpt4 key购买 nike

评论.html:

<template name="comment">
<img src="{{photo}}"> //blank
{{photo}} //blank
</template>

评论.js:

Template.comment.helpers({
photo: function(){
Meteor.call('getPhoto', function(error, result) {console.log(result);return result})
}
});

服务器.js:

Meteor.methods({
getPhoto: function () {
return Meteor.user().services.vk.photo;
}
});

问题:console.log 返回正确的值,但 {{photo}} 为空。问题:为什么 'photo' 是空的?

最佳答案

[更新]

我刚刚意识到这里有什么问题。

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 的事情是你正在设置一个全局变量,如果你有很多评论并且每条评论都需要有一张独特的照片,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;
}
});

Under the hood, each helper starts a new Tracker.autorun. When its reactive dependencies change, the helper is rerun. Helpers depend on their data context, passed arguments and other reactive data sources accessed during execution. -From 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"

关于javascript - meteor 模板助手 : {{keyname}} showing blank,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29485585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com