在Meteor中动态添加文本字段而不使用jquery

时间:2015-04-15 10:37:50

标签: javascript meteor

我有一个简单的申请表。点击一个按钮我只需要添加文本字段,点击另一个按钮,只需动态删除文本字段。

如何在不使用jQuery的情况下在meteor中完成这项工作,因为我看过很多博客都认为在流星上使用jQuery不是一个好习惯。可以告诉我如何在不使用jQuery的情况下实现这一目标。

2 个答案:

答案 0 :(得分:4)

您可以使用反应变量和辅助函数来返回基于该反应变量的数组,以构造模板级{{#each}}语句。响应变量的一个很好的选择是Session变量,因为它内置于Meteor中(您不需要ReactiveVar包或设置自己的依赖项)。

然后,您可以使用事件处理程序根据需要更新反应变量。例如......

//client only code
Template.test.onCreated(function() {
  Session.set('inputs', []); // on page load, set this to have no inputs
});

Template.test.helpers({
  inputs: function () {
    return Session.get('inputs'); // reactively watches the Session variable, so when it changes, this result will change and our template will change
  }
});

// Now we'll set up a click handler to add inputs to our array when we   click the "add" button
Template.test.events({
  'click #add-input': function () {
    var inputs = Session.get('inputs');
    var uniqid = Math.floor(Math.random() * 100000); // Give a unique ID so you can pull _this_ input when you click remove
    inputs.push({uniqid: uniqid, value: ""});
    Session.set('inputs', inputs);
  }
});
// We also need handlers for when the inputs themselves are changed / removed
Template.input.events({
  'click .remove-input': function(event) { 
    var uniqid = $(event.currentTarget).attr('uniqid');
    inputs = Session.get('inputs');
    inputs = _.filter(inputs, function(x) { return x.uniqid != uniqid; });
    Session.set('inputs', inputs);
  },
  'change input': function(event) { 
    var $input = $(event.currentTarget);
    var uniqid = $input.attr('uniqid');
    inputs = Session.get('inputs');
    index = inputs.findIndex(function(x) { return x.uniqid == uniqid; });
    inputs[index].value = $input.val();
    Session.set('inputs', inputs);
  }
});

您的模板看起来像......

<template name="test">
  <button id='add-input'>
    Add Input
  </button>

  {{#each inputs}}
    {{> input}}
  {{/each}}
</template>
<template name='input'>
  <input name='testinput' class='test-input' type='text' uniqid="{{uniqid}}" value="{{value}}">
  <button class='remove-input' uniqid="{{uniqid}}">Remove</button>
</template>

根据Ibrahim在下面的评论,如果要删除文本字段,则需要跟踪文本字段中的值,并在每次删除元素时重新填充它们。您可以查看完整的后续操作here。请注意,为了做到这一点,我作弊并且实际上确实使用了jQuery,因为这样做更容易(至少对我而言)。

无jQuery的替代方案可能涉及绑定onCreated函数以存储对每个input模板实例的引用,您可以从中提取必要的信息,但每this question有{{3}}无法通过Meteor API获取特定模板的所有实例,这是没有jQuery的最简单方法。

编辑: MeteorPad不再存在 - 上面的代码包括使用反应式Session变量处理添加和删除特定输入。我现在正在维护Session变量中输入的当前值,并且每次重新填充输入时(当Session变量更新时),我都会使用这个新的value属性来填充值。

你可以看到不断地从屏幕上读取内容并更新Session变量中的输入数组是非常手动和乏味的 - 这让我觉得这可能不是最好的方法。

答案 1 :(得分:0)

一种可能的解决方案是使用会话变量。单击该按钮时,将会话变量的值设置为您想要的值。在模板中,您可以在任何需要的位置显示会话变量的值。

此外,jquery会自动包含在流星中。在流星应用程序中肯定有使用jquery的地方。甚至可能比在场所使用会话变量更干净。取决于情况。