【问题标题】:In Meteor, the old way to define a helper function is not conflict to the new way?在 Meteor 中,定义辅助函数的旧方法与新方法不冲突吗?
【发布时间】:2016-03-17 12:26:54
【问题描述】:

我是 Meteor 的新手,并尝试遵循“您的第一个 Meteor 应用程序”: http://meteortips.com/first-meteor-tutorial/ 我试图定义一个辅助函数。 在我写的html文件中:

<head>
    <title>Leaderboard</title>
</head>
<body>
    <h1>Leaderboard</h1>
    {{> leaderboard}}
</body>

<template name="leaderboard">
    <!-- Hello World -->
    <!-- {{player}} -->
    <!-- {{otherHelperFunction}} -->
<ul>
    {{#each player}}
        <li>{{name}}:{{score}}</li>
    {{/each}}
</ul> 

{{numOfPlayer}}
</template>

在我写的JS文件中:

if(Meteor.isClient){
    Template.leaderboard.helpers({
        "player": function(){
            // return "Some other text";
            return PlayersList.find();
        },
        "numOfPlayer": function(){
            // return "Some other text";
            return PlayersList.find().count();
        },
        "otherHelperFunction": function(){
            return "Some other funciton";
        }
    })
    Template.leaderboard.player = function(){
    return "Some other text";
    }
    // console.log("Hello client");

}

if(Meteor.isServer){
    console.log("Hello server");
}

PlayersList = new Mongo.Collection('players');

所以在客户端部分的 JS 文件中,我定义了两个“播放器”辅助函数:一个是旧方式,一个是新方式。旧方式实际上是我忘记注释掉但是当我运行这个项目时,网站竟然以“新方式”执行,并且似乎旧方式定义的“播放器”辅助功能并没有影响项目all 并且编译器没有说有任何错误或歧义(因为您可以看到这两个“播放器”辅助函数是为不同的功能定义的)。这是什么原因?是不是因为旧方式定义的辅助函数被新的辅助函数覆盖了?

这是输出接口。

【问题讨论】:

    标签: javascript meteor helper


    【解决方案1】:

    来自Meteor source code

    路径中的第一个标识符通过以下两种方式之一解析:

    1. 索引当前数据上下文。标识符 foo 指的是当前数据上下文对象的 foo 属性。

    2. 作为模板助手。标识符 foo 是指可从当前模板访问的辅助函数(或常量值)。

    模板助手优先于数据上下文的属性。

    您的 Template.leaderboard.player 函数定义在数据上下文中,因此 Blaze 首先查找模板助手。由于您已经定义了帮助程序,因此它具有优先权并被执行。

    【讨论】:

      【解决方案2】:

      这是因为新方式覆盖了旧方式。新方法分配一个新函数引用变量'player'。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-19
        • 2013-06-11
        • 2016-05-09
        • 2015-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多