这是一个简化的示例,但很好地说明了我的问题。我有一个 PIN 码输入,带有数字按钮(1、2、3、4)。我的按钮上的操作应该设置一个属性 pinValue
,该属性将传递到包装的组件 pin-input
中。这就是我的代码的样子:
查看示例: http://ember-twiddle.com/38bd66b63e6745f2ea0d
pin-entry.hbs
{{pin-input pinValue=pinValue}}
{{#each numbers as |num|}}
<button {{action "addNumber" num}}>{{num}}</button>
{{/each}}
pin-entry.js
pinValue: null,
numbers: [1, 2, 3, 4],
actions: {
addNumber: function (number) {
this.set('pinValue', number);
this.notifyPropertyChange('pinValue');
}
}
pin-input.hbs
<input type=text value={{value}}>
pin-input.js
value: null,
pinValue: null,
onInsertAddObserver: function() {
// trying to manually subscribe to pinValue here.
// * from stackOverflow answer
var controller = this.get('targetObject');
controller.addObserver('pinValue', this, this.onDataChange)
}.on('didInsertElement'),
onDidChangeInput: function() {
var current = this.$('input').val();
this.set('value', current + this.get('pinValue'));
}.observes('pinValue')
问题是当尝试连续输入重复的数字时(例如 1233 将停止在 123)。我似乎无法强制更改属性,以便 onDidChangeInput
将火。 addObserver
方法来自另一篇文章*。
*一些想法取自这里,但对我没有帮助:EmberJS notifyPropertyChange not making it to observer?
最佳答案
自从数据下降和行动上升以来
我会选择这样的东西。
{{pin-input pinCode=current}} // Explaining it later
{{#each numbers as |num|}}
{{pin-number nr=num numberChanged="numberChanged"}}
{{/each}}
pin-number.js
actions: {
addNumber: function (number) {
this.sendAction('numberChanged', number); // To the controller
}
}
controller.js
actions: {
numberChanged: function(newNr) {
var current = this.get('current');
if(Ember.isNone(current) || current.length >= 4) {
this.set('current', newNr);
} else {
this.set('current', this.get('current') + "" + newNr);
}
}
现在我们将 current 绑定(bind)到 引脚输入
{{pin-input pinCode=current}}
关于javascript - Ember 的 notifyPropertyChange() 不会触发包装组件的观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397520/