在新建元素的流星模板中重新应用事件监听器

时间:2015-02-01 23:54:29

标签: jquery meteor

某些背景信息:在我的应用中,我有这些输入文本框,当您输入它们时,它会使用会话来保存一个反应变量,以便用户可以看到实时预览他们正在打字。

我想让用户点击按钮添加新的输入框。每当用户输入新的输入框时,它也应该以与第一个输入框相同的方式生成实时预览。但是,似乎事件处理程序不适用于那些新创建的元素。因此,在我再次在原始输入框中键入内容之前,实时预览不会更新。

Template.makeEntry.helpers({
    goals: function() {
        return Session.get('todayGoals');
    }
});

Template.makeEntry.events({
  'input .goal': function(e) {
    var tempGoals = [];
    $('.goal').each(function(i){

        tempGoals.push($(this).val());
    });
    Session.set('todayGoals',tempGoals);
  },
  'click .add-goal': function(e) {

    var lastGoal = $('.goal').last();

    $('<input class="goal" type="text" name="goal" placeholder="Type your goal here...">').insertAfter(lastGoal);
  }
});

Template.makeEntry.rendered = function(){
    Session.set('todayGoals',[]);
}

HTML:

<template name="makeEntry">
    <h1>Sunday, February 1st</h1>
    <hr>
    <input class="goal" type="text" name="goal" placeholder="Type your goal here...">
    <button class="add-goal">Add</button>
    {{#if goals}}
        <ul>
            <li>Today's Goals
                <ul>
                    {{#each goals}}
                        <li>{{{this}}}</li>
                    {{/each}}
                </ul>
            </li>
        </ul>
    {{/if}}
</template>

1 个答案:

答案 0 :(得分:3)

尽量不要在Blaze之外操纵DOM。

Template.makeEntry.created = function(){
  Session.set('todayGoals',[""]);
}

Template.makeEntry.events({ 
  'click .add-goal': function(){
    var goals = Session.get('todayGoals');
    goals.push("");
    Session.set('todayGoals', goals);
  }
});

Template.makeEntry.helpers({
  'goal': function(){
    return Session.get("todayGoals");
  } 
});

并在html中

<template name="makeEntry">
  ...
  {{#each goal}}
    ... do something with goal
    <input class="goal" type="text" name="goal" placeholder="Type your goal here...">
  {{/each}}
</template>