无法使用流星显示光标返回的值

unable to display the returned value from a cursor using meteor

本文关键字:光标 返回 显示 流星      更新时间:2023-09-26

我有一个模板,看起来像这样:

<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;
                    }
                });
            }
        });
    }
});
});

当我记录结果时,我在控制台中得到了正确的对象,但我的模板仍然是空的。返回的对象中不存在列"name"。像这样:

[Object, Object]
0: Object
_id: "Mcqf3Hh2ARH2NJsDB"
name: "item 1"
1: Object
_id: "e9mkxgNqHgM3czMvE"
name: "item 2"

您必须记住javascript是异步的。当您在回调中使用"return"时,它不会返回到原始方法调用。它将返回回调方法。

您必须使用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);
    ....
    }
}