我有一个简单的组件,它是tagName
的{{1}}元素。
到目前为止没问题。现在我想观察输入的value属性。每当输入改变时,我想发射一个观察者。
为什么这不起作用?
可以找到一个JSFiddle here。
<script type="text/x-handlebars">
{{my-input}}
</script>
<script type="text/x-handlebars" id="components/my-input">
</script>
var App = Ember.Application.create();
App.MyInputComponent = Ember.Component.extend({
tagName: 'input',
attributeBinding: ['value'],
onChange: Ember.observer('value', function() {
console.log('change');
})
});
答案 0 :(得分:2)
免责声明:此解决方案适用于OP(ember-1.0.0-rc.6.js)使用的ember版本,在未来版本中概念保持不变只有语法有点改变。
(版本1.13.6的示例https://emberjs.jsbin.com/xuhavokubi/edit?html,js,output,最后发布的代码)
原始代码的问题如下,
1.绑定属性的属性是attributeBindings
2. Ember.observer
在未来的版本中运行良好,但似乎在这个版本的组件中不起作用(ember-1.0.0-rc.6.js)
3.使用observes
4.添加处理dom值更改的函数并通知ember属性
<强>实施例中,强>
版本为ember-1.0.0-rc.6.js (http://jsfiddle.net/3vre965u/)
<强> HBS 强>
<script type="text/x-handlebars">
{{my-input}}
</script>
<script type="text/x-handlebars" id="components/my-input">
the value:{{value}}<br/><button {{action "changeTheValue"}}>change value</button>
<button {{action "displayTheValues"}}>display values</button>
</script>
<强> JS 强>
var App = Ember.Application.create();
App.MyInputComponent = Ember.Component.extend({
tagName: 'input',
attributeBindings: ['value'],
changeTheValue:function(){
this.set('value',Date.now());
},
displayTheValues:function(){
alert("ember value:\n"+this.get("value")+"\nDOM value:\n"+this.$().val());
},
//catches dom event
//fires only when focused lost
change:function(event){
this.set("value",event.target.value);
},
//catches dom event
keyUp:function(event){
this.set("value",event.target.value);
},
//works like this in future versions, does not work in current version
onChange: Ember.observer('value', function() {
console.log('change');
}),
//alternative observer that works fine in current version
onChange2: function(){
console.log('change2');
}.observes('value')
});
版本1.13.6 (https://emberjs.jsbin.com/xuhavokubi/edit?html,js,output)
<强> HBS 强>
<script type="text/x-handlebars">
{{my-input viewName="test"}}
<br/>
the value:{{view.test.value}}<br/><button {{action "changeTheValue" target="view.test"}}>change value</button>
<button {{action "displayTheValues" target="view.test"}}>display values</button>
</script>
<script type="text/x-handlebars" id="components/my-input">
</script>
<强> JS 强>
var App = Ember.Application.create();
App.MyInputComponent = Ember.Component.extend({
tagName: 'input',
attributeBindings: ['value'],
actions:{
changeTheValue:function(){
this.set('value',Date.now());
},
displayTheValues:function(){
alert("ember value:\n"+this.get("value")+"\nDOM value:\n"+this.$().val());
}
},
//catches dom event
//fires only when focused lost
change:function(event){
this.set("value",event.target.value);
},
//catches dom event
keyUp:function(event){
this.set("value",event.target.value);
},
onChange: Ember.observer('value', function() {
console.log('change');
}),
//alternative observer
onChange2: function(){
console.log('change2');
}.observes('value')
});