Reputation: 15742
I want to use my own Ember.View implementation but unfortunately the valueBinding does not work (it works with the build-in ones)
App.NumberView = Ember.View.extend({
tagName: 'input',
attributeBindings: ['type', 'min', 'max', 'step', 'value', 'placeholder'],
type: 'number',
step: '0.01',
min: '0',
max: null,
placeholder: null,
value: ''
});
In the template:
{{view App.NumberView id="value" valueBinding="value" placeholder="39.90"}}
<button type="button" {{action submit}}>submit</button>
In the controller:
App.SomeController = Ember.Controller.extend({
submit: function() {
// returns undefined
this.get('value');
}
});
What is missing on my own NumberView to support valueBinding?
Bodo
Upvotes: 0
Views: 1744
Reputation: 6769
I got it to work natively. There are a couple things wrong here. It didn't work because when you use this.get('value');
in the controller, it's looking for the attribute 'value' in the controller itself which didn't exist, thus the undefined. Also, 'value' is a reserved property of the Ember View so you can't treat it as the input's value property.
What you have to do is set valueBinding
of the view to a custom attribute/property in your controller. This will bind the View's value to the Controller (and not the View's Input's value). In order to bind the actual html input's value, you have to manually propagate the changes and set the View's value. I'll explain after this code chunk.
HTML HBS:
{{view App.NumberView valueBinding="cValue" placeholder="39.90"}}
Javascript:
App.NumberView = Ember.View.extend({
didInsertElement: function(){
this.change = $.proxy(this._change, this);
},
tagName: 'input',
attributeBindings: ['type', 'min', 'max', 'step', 'placeholder'],
type: 'number',
step: '0.01',
min: '0',
max: null,
value: null,
_change: function(){
this.set('value',this.$('input').get('context').value);
console.log('View input value is --> ' + this.$('input').get('context').value);
}
});
App.IndexController = Ember.Controller.extend({
cValue: null,
submit: function() {
alert(this.get('cValue'));
}
});
So basically, the Controller has a property called cValue, which is binded to the value
of NumberView. In NumberView, I used didInsertElement() function to attach my own function call _change()
to the input's change event. In _change()
, I set and update the NumberView's value to the input's current value.
Here is a working JSBin
Upvotes: 1
Reputation: 23322
Instead of extending Ember.View
, you could better extend the Ember.TextField
directly.
For example:
App.NumberView = Ember.TextField.extend({
attributeBindings: ['type', 'min', 'max', 'step', 'value', 'placeholder'],
type: 'number',
step: '0.01',
min: '0',
max: null,
placeholder: null,
value: ''
});
See here for a working jsbin.
Hope it helps.
Upvotes: 1