【问题标题】:Meteor use fetch or find in template helper functions?Meteor 在模板辅助函数中使用 fetch 或 find 吗?
【发布时间】:2013-05-12 04:53:09
【问题描述】:

在流星模板辅助函数中,如果我返回 findfetch 的结果,在性能、重新渲染次数或其他方面是否有任何差异?

例如find方法:

Template.players.topScorers = function () {
  return Users.find({score: {$gt: 100}}, {sort: {score: -1}});
};

或者添加一个 fetch:

Template.players.topScorers = function () {
  return Users.find({score: {$gt: 100}}, {sort: {score: -1}}).fetch();
};

目前在docs 中使用的是仅查找方法,但我看到很多其他人使用fetch

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    这就是我们在 Oodles Technologies 中所遵循的。

    要定义帮助程序,只需转到您的模板 js 文件,例如,如果您的模板名称为 allInventory,那么只需转到 allInventory.js 文件并按如下方式编写帮助程序:-

    Template.allInventory.helpers({
    
    })
    

    在这个帮助器中创建一个函数,你可以在其中放置从数据库或会话或其他服务获取数据的逻辑,而不是在你的 html 中使用它:-

        Template.allInventory.helpers({
            productDetails: function() {
                  return Session.get('dbData');
            }
        })
    
    On html side you just need to use the function name as follows:-
    
    {{#each productInfo in productDetails}}
    
            <div class="imgb"><img src="{{productInfo.image_url}}"></div>
               {{productInfo.item_name}}
               {{productInfo.seller_sku}}
                {{productInfo.quantity}}
                {{productInfo.price}}
    
    <a type="button" class="full-view text-success"><i id="fullView" data="{{productInfo._id}}" class="fa fa-eye"></i></a>
    
              {{/each}} 
    

    正如您在上面的 productDetails 中看到的,您的帮助程序类中的函数名称可以通过该名称直接访问,您可以通过该名称获取要在 Html 上呈现的数据,并且您可以通过 html 模板中的每个循环遍历它。

    【讨论】:

      【解决方案2】:

      是的。

      通过使用 fetch,您可以在现场注册对整个查询结果集的依赖。通过使用find 以及稍后使用{{#each}} 进行迭代,每个文档上都分别注册了一个依赖项。所以当一个文档发生变化时,只会重新渲染相关的代码。使用fetch 时,更改结果集中的任何文档都会重新呈现您使用fetch 的整个范围。

      对于小的结果集,它没有任何区别。对于频繁更改的较大集合,它可能会减慢计算速度并导致不希望的视觉伪影。

      我写了一个post 可以帮助你理解它(虽然它没有直接回答你的问题)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 1970-01-01
        • 1970-01-01
        • 2013-08-08
        • 2018-08-22
        • 1970-01-01
        • 2014-12-24
        相关资源
        最近更新 更多