具有事件生成的输入的流星结合值 [英] Meteor binding values for inputs with event generation

查看:118
本文介绍了具有事件生成的输入的流星结合值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单输入,其值绑定到无效数据源:

I have a form input with a value bound to a reactive data source:

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

我想在输入上观看更改事件:

I want to watch 'change' events on the input:

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

如果我直接在输入中更改值,这可以正常工作。但是,如果值反应更改,则更改事件不会触发。

This works fine if I change the value directly in the input. However, if the value changes reactively, the change event doesn't fire.

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

What's the best way to bind values to form elements so that the 'change' event fires if the reactive data source changes?

推荐答案

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

The Optimum Solution would be to use manuel:viewmodel. You keep the state of the UI in a javascript object and bind the UI elements to properties of that object.

示例:

首先使用添加程序包到流星添加manuel:viewmodel

然后在Html中以下内容:

Then in the Html do the Following :

<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文件中进行必要的绑定

Then in the Javascript file do the Necessary Bindings

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元素的值绑定到viewmodel。

Here we're binding the value of the input/text element to the property 'first' of the viewmodel.

结果是viewmodel对象将与输入框保持同步。如果您更改texbox中的值,则viewmodel的first属性的值也将更改,反之亦然。

The result is that the viewmodel object will be kept in sync with the input box. If you change the value in the texbox then the value of the viewmodel's 'first' property will also change and vice versa.

有关详细信息 http://viewmodel.meteor.com/

这篇关于具有事件生成的输入的流星结合值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆