在模板级别的个人订阅,我滥用模板级订阅有多糟糕?

时间:2015-03-25 23:03:30

标签: meteor handlebarshelper

我已经懒得加入以下帮手:

// Given a userId, show the username
Handlebars.registerHelper('username', function(userId) {
    // This seems extremely wasteful
    Template.instance().subscribe('user', userId);

    var user = Meteor.users.findOne({ _id: userId });
    if (user) {
        return user.username;
    }   
    return "";
});

对模板级订阅而言,对我的原型非常有用!我找不到任何人谴责这个想法,但也许那是因为它是如此愚蠢,没有人会考虑这样做。你有这种模式的经验,你能推荐它吗?

我特别担心订阅量,以及它们可能导致的大量重新渲染。

2 个答案:

答案 0 :(得分:2)

从我的观点来看,这不是最聪明的事情。为什么要重新发明轮子 已经定义了这种助手。

{{currentUser}}

http://docs.meteor.com/#/full/template_currentuser

需要用户名... {{currentUser.username}}

答案 1 :(得分:0)

普通助手的想法可能不是那么糟糕,但我会将订阅和名称检索分开,只让订阅运行一次:

Handlebars.registerHelper('userSubscribe', function(userIds) { // make userIds an array
    Template.instance().subscribe('users', userIds); // change your publishing function to take the array
});

Handlebars.registerHelper('userName', function(userId) { 
    var user = Meteor.users.findOne({ _id: userId });
    if (user) {
        return user.username;
    }   
    return "";
});

然后,每个模板负责发送它实际想要订阅的用户列表。让我们假设您有一个帖子集合,为简单起见,它具有以下格式:

{author: user_id, commenter: user_id, text: String}

然后你应该可以这样使用它:

// JS
Template.myTemplate.helpers({
  getMyUsers: function() { return [this.author, this.commenter]; }
});

// HTML
<template name='myTemplate'>
  {{userSubscribe getMyUsers}}
  The author is {{userName author}} and the commenter is {{userName commenter}}
</template>

它可能仍然不理想,但它应该只重新渲染一次,而不是每个用户在数据到达客户端时要查找其名称的用户。