【问题标题】:How to access elements in the current template in meteor?如何在流星中访问当前模板中的元素?
【发布时间】:2015-12-18 13:19:57
【问题描述】:

我有一个这样的模板,

<template name = "foo">
    <p id="loading" >LOADING...</p>
    <p> {{theResult}} </p>
</template>

这就是我创建 foos 的方式,

 // foos = [a, b, c, d]. With each button click I add a new item to the array
 {{#each foos}}
    {{> foo .}}
 {{/each}}

以及 foo 的工作原理,

Template.foo.created = function(){
    var name = Template.currentData();
    api_call(name, function(err, result){
        Session.set(name, result);
    }); 
}  

Template.foo.helpers({
        'theResult': function(){
            var name = Template.currentData();
            if(Session.get(name)) {
                $("#loading").hide();
                return Session.get(name);
            } else {
                return "";
            }
        }
    })

所以我的期望是当数据来自 api_call 时,隐藏“LOADING...”参数,并在结果中显示结果。

结果显示正确。我的问题是“正在加载...”仅隐藏在最顶层的 foo 上。不是其他的。

我该如何解决这个问题?

编辑: 正如建议的那样,

$("#loading").hide();

我用过,

Template.instance().$("#loading").hide();

这也没有用:)

【问题讨论】:

    标签: node.js meteor meteor-blaze meteorite meteor-helper


    【解决方案1】:

    我就是这样做的

    模板...如果未定义theResult,将呈现else路径。

    <template name="foo">
        {{#with theResult}}<p> {{this}} </p>
        {{else}}<p id="loading" >LOADING...</p>
        {{/with}}
    </template>
    

    Javascript...theResult 是一个简单的 Session.get 调用

    Template.foo.helpers({
        theResult: function(){
            var name = Template.currentData();
            return name && Session.get(name);
        }
    });
    

    【讨论】:

      【解决方案2】:

      感谢 Meteor 模板引擎,您可以访问模板范围的 jQuery 对象,该对象只会返回相应模板中的元素。

      Template.foo.helpers({
        'someText': function(){
          var template = Template.instance();
          template.$('p').changeSomeattr();
          return Session.get('myPara');
        }
      });
      

      【讨论】:

      • 谢谢@saimeunt,实际上这对我不起作用。我有一个按钮,当我单击它时,它会在页面中添加一个新的 foo 并且该 foo 会在一段时间后显示一些数据,然后我想更改 foo 的颜色。你的解决方案效果很好,当我添加一个时,等到它改变颜色,然后同样添加第二个......但是当我同时添加它们时,只有顶部会改变颜色。我可能错过了什么或如何解决这个问题? ://
      • 你能在你最初的问题上发布更多代码,没有占位符吗?
      • 编辑了代码。 @saimeunt 你现在可以看看吗? :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2023-03-27
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多