我有一个看起来像这样的模板:
<template name="item_list">
{{#each items}}
<div>{{name}}</div>
{{/each}}
</template>
该模板具有一些客户端js代码:
Template.item_list.helpers(
{
items: function() // find items
{
Meteor.call('getId', Meteor.userId(), function(error, result)
{
if(error)
{
console.log(error.message);
}
else
{
console.log(result); // correct id returned
Meteor.call('findItemById', result, function(error, result)
{
if(error)
{
console.log(error.message);
console.log(error.stack);
}
else
{
console.log(result); // this contains 2 objects with the correct values
return result;
}
});
}
});
}
});
});
当我记录结果时,我在控制台中得到了正确的对象,但是我的模板仍然为空。返回的对象中确实存在“名称”列。像这样:
[Object, Object]
0: Object
_id: "Mcqf3Hh2ARH2NJsDB"
name: "item 1"
1: Object
_id: "e9mkxgNqHgM3czMvE"
name: "item 2"
您必须记住javascript是异步的。当您在回调中使用'return'时,它不会返回到原始的Method调用。它只会返回到回调方法。
您必须使用Session
变量来连接数据并运行创建模板的初始调用。
Template.item_list.helpers(
{
items: function() {
return Session.get('items');
}
});
Template.item_list.created = function() {
Meteor.call(... function(err,result) {
....
Session.set('items', result);
....
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句