如何使`<input />的内部状态无效?

时间:2016-08-19 14:50:46

标签: ember.js

假设我在ember.js中有一个简单的输入:

<input value={{val}} />

然后在那里输入文字。如何使用代码强制执行ember将<input> 重置为相同的值

简单的this.notifyPropertyChange('val');set(this, 'val', get(this, 'val')); 工作。

你必须做这样的事情:

let oldVal = get(this, 'val');
set(this, 'val', 'some dummy value');
Ember.run.later(() => set(this, 'val', oldVal));

但那确实很糟糕。

让我解释为什么我需要这个。一个示例是输入,其中用户只能输入字母AB,而不能输入C。做这样的事情会很好:

HBS

<input value={{val}} oninput={{action 'update' value='target.value'}} />

JS

val: '',
actions: {
    update(newVal) {
        if(!newVal.includes('C')) {
            set(this, 'val', newVal);
        } else {
            // reset the input to the last valid value.
            // so basically do
            set(this, 'val', get(this, 'val'));
            // or
            this.notifyPropertyChange('val');
            // but neither does update the <input>.
            // the only way is this:
            let oldVal = get(this, 'val');
            set(this, 'val', 'some dummy value');
            Ember.run.later(() => set(this, 'val', oldVal));
            // because this enforces the <input> to forget its internal state.
            // is there any other way to do this?
        }
    }
}

3 个答案:

答案 0 :(得分:1)

我发现了两种不同的方法:

  1. 将动作侦听器的dom值重置为之前的值。 (如果我没有错,那就是ember-one-way-controls的方式。请看看这个插件的代码。)
  2. 处理keyPress,keyDown或keyUp函数,如果输入无效则返回false。 (这就是js方式。)
  3. 我已在this twiddle实施了第二个选择。您可以根据规则更改sanitize功能。

    您可以看到有关数字输入组件的previous discussions(可能相关但不同)。

答案 1 :(得分:0)

我不知道这是否适合你,但无论如何我会把它扔给你。如果这是我的问题,这就是我接近的方式。另外请注意,我使用的是恐龙版的ember(1.3)

{{input value=val action="createNote"}}

textChanged: function(){

 if(!newValue.includes('C')) {
        //whatever you want 
    } else {

    }
}.observes("newValue"),

  actions: {
    updateValue: function(){
      this.set('newValue', val);
    } 

  }

答案 2 :(得分:0)

如果您不想更改val属性的内部状态,则必须保留val属性作为其属性,并自行更新DOM元素中的val。 (注意:设置相同的值不会触发重新渲染)。 Ember-Twiddle

<强>组件/我的-component.js

import Ember from 'ember';
const {get,set} = Ember;

export default Ember.Component.extend({
  val:'',
  actions:{
    update(newVal){      
      let oldVal = get(this, 'val');      
      console.log('newVal-',newVal+' oldVal-',oldVal);
      if(!newVal.includes('C')) {
            set(this, 'val', newVal);
        } else {          
          this.$('#fieldId').val(oldVal);
        }
    }
  }
});

<强>模板/组件/我的-component.hbs

<input id='fieldId' name='fieldName' value={{val}} oninput={{action 'update' value='target.value'}} />
{{val}}
{{yield}}

<强>模板/ application.hbs

{{my-component }}