【问题标题】:Meteor data context within templates vs helpers模板与助手中的流星数据上下文
【发布时间】:2017-02-01 03:23:27
【问题描述】:

试图更好地理解数据上下文在 Meteor 中的工作原理,因为我无法弄清楚我面临的这个问题。在任何地方都没有找到明确的答案。我有以下模板

<template name="list">
  {{#each listItem}}
    {{> listItemDetail}}
  {{/each}}
</template>

<template name="listItemDetail">
  <p>{{_id}} {{title}}</p>
  <p>{{idViaHelper}}</p>
</template>

在我的 Javascript 中我有

Template.list.helpers({
    'listItem': () => {
        return List.find().fetch();
})

Template.listItemDetail.helpers({
    'idViaHelper': () => {
        return this._id
})

就我对 Meteor 中数据上下文的理解而言,使用 #eachlistItemDetail 模板的每个实例的上下文设置为从 listItem 帮助器返回的文档。

当在listItemDetail 模板中使用{{_id}} 时,这正如我所期望的那样工作,显示文档的ID。

但如果我尝试通过使用this._id 的助手{{idViaHelper}} 获得相同的_id,我会得到undefined。当我尝试console.log(this) 时,它告诉我this 指的是Window 对象。但我不知道为什么。发生了什么,为什么模板助手中没有获取数据上下文?

这是我的第一篇文章,感谢您的帮助!

【问题讨论】:

    标签: templates meteor helpers


    【解决方案1】:

    您对 Meteor 数据上下文流的看法是正确的。 你正在做的工作。

    您只会忘记 this 在 lambda 函数中的含义。

    阅读 MDN 的 Lexical this 部分,它比我说的更好解释:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    对于您的情况,直接从您的 this on helpers 获取数据上下文的更简单方法是通过通常的匿名函数。

    试试吧:

    Template.listItemDetail.helpers({
        'idViaHelper': function(){
            return this._id
    })
    

    就是这样。

    你运气不好,这里没有流星的问题。

    您可能会发现有用的其他相关问题:meteor helper functions, lambdas and lexical this

    【讨论】:

    • 谢谢朱利安。我认为箭头函数纯粹是 ES2015 中的语法变化(并且声明函数的旧方式将被弃用),但我想如果两者之间存在技术差异和用途,那么它们可能都会继续存在。跨度>
    【解决方案2】:

    Julien Leray 在他关于词汇 this 的回答中是正确的。使用 lambda 表达式时会丢失数据上下文。但是,Meteor 为您提供了无需词法 this 即可访问模板数据的方法,即:

    Template.list.helpers({
      'listItem': () => List.find().fetch();
    });
    
    Template.listItemDetail.helpers({
      'idViaHelper': () => Template.currentData()._id
    });
    

    您可以同时使用Template.currentData()Template.instance().data

    另外,请注意,如果您的 lambda 表达式只包含一个 return 语句,您可以使用我上面所做的快捷语法。

    // ECMAScript 5
    var myFunc = function (a, b, c) {
      return b * a - c;
    };
    

    变成:

    // ECMAScript 6
    const myFunc = (a, b, c) => b * a - c;
    

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 2019-06-14
      • 2015-09-05
      • 2014-12-30
      • 2018-01-03
      • 1970-01-01
      相关资源
      最近更新 更多