【问题标题】:meteor template argument value differs between helper and event流星模板参数值在助手和事件之间不同
【发布时间】:2017-09-23 15:42:39
【问题描述】:

我想包含一个带有参数的 Blaze 模板,然后在事件中使用参数值。问题是,当我第二次使用不同的参数包含模板时,我会从事件中模板的第一个实例获取参数值。

模板:

<template name="UploadFormLayoutImage">
    <form class="uploadPanel">
        <input type="file" name="fileupload" id="input-field">
        <label for="input-field">Upload file</label>
    </form>
</template>

包括:

{> UploadFormLayoutImage layoutArea="area1"}}
{> UploadFormLayoutImage layoutArea="area2"}}

js:

Template.UploadFormLayoutImage.onCreated(function(){
   this.currentArea = new ReactiveVar;
   this.currentArea.set(this.data.layoutArea);
});


Template.UploadFormLayoutImage.helpers({
    layoutArea: function() {
        return Template.instance().currentArea.get(); //Returns the correct argument value for each instance of the template.
    }
});


Template.UploadFormLayoutImage.events({
    'change input[type="file"]': function(e, instance) {
        e.preventDefault();
        console.log(instance.data.layoutArea); //Allways returns 'area1'
    }
});

我在这里缺少什么? (这是我的第一个 Stackoverflow 问题。请温柔:))

【问题讨论】:

  • 请分享 UploadFormLayoutImage 模板。您是否使用此模板中的参数调用助手?
  • @Ankit 我已经添加了模板。我实际上不需要模板中的助手。我只需要在事件中获得与助手中相同的值。我将在创建 Mongo 文档时使用该值。感谢您的评论。

标签: meteor meteor-blaze


【解决方案1】:

如果将事件方法中的 instance.data.layoutArea 更改为 this.layoutArea 会怎样?

【讨论】:

  • 不幸的是,这会产生相同的结果。
  • 嗯。好吧,您在事件方法中将this 值设置为实例,并且它被附加到input[type="file"],这似乎包括第一个实例{&gt; UploadFormLayoutImage layoutArea="area1"}}。要解决此问题,您可以在您的 events 方法中 console.log e 和 instance 以查看传入的内容。如果它仅从第一个实例传入数据,您可以尝试将侦听器更改为除此之外的其他内容更改,例如单击,因为我发现从浏览器到浏览器的更改有点挑剔。
【解决方案2】:

为了使代码示例易于阅读,我删除了导致问题的部分。我正在为输入字段使用标签,因此输入字段有一个 id,在重复模板时当然不行。

我现在使用 layoutArea-helper 作为 id 值,一切正常。

<template name="UploadFormLayoutImage">
    <form class="uploadPanel">
        <input type="file" name="fileupload" id="{{layoutArea}}">
        <label for="{{layoutArea}}">Upload file</label>
    </form>
</template>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-24
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    相关资源
    最近更新 更多