MeteorJS Tracker:订阅后如何返回值?

时间:2016-01-20 17:37:51

标签: meteor scope tracker ddp

使用Tracker.autorun()方法遇到此问题:

Template.registerHelper('getUserName', (userId) => {

    let userName = '';
    Tracker.autorun((tracker) => {
        if (userId) {
            let subscription = Meteor.subscribe('userName', userId);
            if (subscription.ready()) {
                tracker.stop();
                let user = Meteor.users.findOne({_id: userId}, {fields: {emails: 0}});
                userName = user.services.facebook.name;
            }
        }
    });
    return userName;

});

我想从发布中返回用户名,但是,范围很棘手,因为当Tracker仍在订阅数据时,帮助程序返回一个空字符串。

我试过这个:

Template.registerHelper('getUserName', (userId) => {

    let subscription;
    Tracker.autorun((tracker) => {
        if (userId) {
            subscription = Meteor.subscribe('userName', userId);
        }
    });
    if (subscription.ready()) {
        let user = Meteor.users.findOne({_id: userId}, {fields: {emails: 0}});
        return user.services.facebook.name;
    }

}); 

但是订阅还没有方法.ready()

有关如何使用示波器的任何想法吗?我记得闭包很有用。

1 个答案:

答案 0 :(得分:1)

我认为您希望将订阅从您的帮助中移出。最好留给在onCreated()函数中调用帮助器的模板。请查看此链接以获取帮助:http://guide.meteor.com/data-loading.html

所以你的助手会是这样的:

// application begins
void Application_Start(Object s, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("session_id", System.Type.GetType("System.String")));
    dt.Columns.Add(new DataColumn("username",   System.Type.GetType("System.String")));
    dt.Columns.Add(new DataColumn("login_time", System.Type.GetType("System.DateTime")));
    dt.Columns.Add(new DataColumn("ip_address", System.Type.GetType("System.String")));

    Application["visitorTable"] = dt;
}

// browser's first visit to the page, (session starts)
void Session_Start(Object s, EventArgs e)
{
    {
        Application.Lock();

        DataRow dr = dt.NewRow();

        dr["session_id"] = (System.String)HttpContext.Current.Session.SessionID; // session id
        dr["ip_address"] = Request.ServerVariables["SERVER_NAME"]; //ip-address

        dt.Rows.Add(dr);

        dt = (Database)Application["visitorTable"];

        Application["visitorTable"] = dt;

        Application.UnLock();
    }
}

然后在您的模板中执行:

Template.registerHelper('getUserName', (userId) => {
    let user = Meteor.users.findOne({_id: userId}, {fields: {emails: 0}});
    if( user && user.services && user.services.facebook) {
        return user.services.facebook.name;
    }
});