Meteor:如何接受一组表单字段中的用户输入

kru*_*ubo 2 forms meteor

流星新手.我有一个有几个领域的表格

<template name="addcityform">
  <form name="addcity">
    <input name="city" class="city" type="text">
    <input name="population" class="population" type="text">
    <input type="Submit" value="Add City">
  </form>
</template>
Run Code Online (Sandbox Code Playgroud)

我只想将字段插入到数据库中,但我对如何操作感到难过.以下是我几次尝试后的目前情况:

Template.addcityform.events({
  'submit .addcity' : function(evt, template) {
    Cities.insert({
      city: template.find('input.city').value,
      population: template.find('input.population').value
    });
  }
});

// this gives: Uncaught TypeError: Cannot read property 'value' of null 
Run Code Online (Sandbox Code Playgroud)

我看到了一些使用Session.set和的例子document.getElementById,但由于可能存在名称空间冲突,这对我来说似乎很笨拙.我想以"正确的方式"执行此操作,以便稍后可以扩展,例如,我可以将表单的多个实例放在页面上,它们应该彼此独立.这样做的"正确方法"是什么?

sai*_*unt 6

您在"提交表单"处理程序中缺少event.preventDefault(),否则页面将重新加载并破坏Meteor的单页应用程序体验.

我会做的事情如下:

<template name="addcityform">
    <form>
        <input name="city" class="city" type="text">
        <input name="population" class="population" type="text">
        <button type="submit">Add City</button>
    </form>
</template>

Template.addcityform.events({
    "submit form": function(event, template) {
        event.preventDefault();
        Cities.insert({
            city: template.find(".city").value,
            population: template.find(".population").value
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

Meteor模板的优点在于它们中使用的css选择器是当前模板的本地选项,这意味着"提交表单"将始终引用"在封闭模板中提交表单元素的事件",因为您只有一个表单.模板.这同样适用于模板实例.find方法:它将返回与模板或其子模板中的css选择器匹配的元素.这允许您拥有addcityform的多个实例,这些实例将彼此独立.