具有事件生成的输入的 Meteor 绑定值

Meteor binding values for inputs with event generation

我有一个表单输入,其中的值绑定到反应式数据源:

<input type="text" name="first-name" id="first-name" required value="{{currentUser.profile.firstName}}" />

我想在输入上观看 'change' 个事件:

$('#first-name').change(function() { alert('Value changed!'); });

如果我直接在输入中更改值,这会很好用。但是,如果值被动更改,则不会触发更改事件。

将值绑定到表单元素的最佳方式是什么,以便在响应式数据源更改时触发 'change' 事件?

最佳解决方案是使用 manuel:viewmodel。您将 UI 的状态保存在 javascript 对象中,并将 UI 元素绑定到该对象的属性。

示例:

首先用meteor add manuel:viewmodel

将包添加到项目中

然后在 Html 中执行以下操作:

<template name="loginBox">
  First Name: <input type="text" data-bind="value: first"/>
  <br/>
  Last Name: <input type="text" data-bind="value: last"/>
  <div data-bind="text: greeting"></div>
  <a data-bind="enabled: canEnter, hover: showError" class="btn-primary">Enter Site</a>
  <span data-bind="text: errorText" class="text-error"></span>
</template>

然后在 Javascript 文件中执行必要的绑定

Template.loginBox.viewmodel({
  first: '',
  last: '',
  greeting: function() {
    return "Hello " + this.first() + " " + this.last();
  },
  canEnter: function() {
    return !!this.first() && !!this.last();
  },
  showError: false,
  errorText: function() {
    if (this.canEnter() || !this.showError()) {
      return '';
    }
    return "Please enter your first and last name";
  }
});

这里我们将 input/text 元素的值绑定到视图模型的 属性 'first'。

结果是视图模型对象将与输入框保持同步。如果您更改 texbox 中的值,那么视图模型的 'first' 属性 的值也会更改,反之亦然。

更多信息http://viewmodel.meteor.com/

这是我的初步解决方案,我对它不是特别满意:

Template.signUpPersonalDetails.rendered = function() {
  this.autorun(function() {
    if (Meteor.user() && Meteor.user().userAccount) {
      var userAccount = Meteor.user().userAccount;
      $('#first-name').val(userAccount.firstName).change();
      $('#last-name').val(userAccount.lastName).change();
      $('#email').val(userAccount.email).change();
      $('#phone-number').val(userAccount.phoneNumber).change();
      $('#postcode').val(userAccount.shippingPostcode).change();
    }
  });
};