Asked By: Anonymous
In my app a model object myModelObject
with a property foo
is created. Initially foo
is set to an integer. foo
can be modified in an input form field.
Modifying foo
in this form field to be some other integer results in foo
changing to be a string.
- Example w/o Ember Data: http://jsbin.com/qahafapixebe/3/edit
- Example with Ember Data: http://jsbin.com/nujesovugudo/2/edit
Is there a way to ensure that a property stays an integer after being modified via form field?
Note: App.myModelObject.set("foo", 23)
results in foo
staying an integer.
I use Ember 1.7.0.
Solution
Answered By: Anonymous
First of all, the <input type="range">
control’s value
property is a string. To quote the W3C wiki:
The range state represents a control for setting the element’s value to a string representing a number.
I don’t believe you will get past that fundamental constraint of the browser.
Secondly, your question is about how to enforce the value to be a Number
. You could do it this way:
App.NumericInputComponent = Ember.TextField.extend({
init: function() {
this.set('value', this.get('numericValue'));
this._super();
},
numericValue: 0,
updateNumeric: function() {
this.set('numericValue', Number(this.get('value')));
}.observes('value'),
updateValue: function() {
var val= Number(this.get('numericValue'));
this.set('value', Number.isNaN(val)?null:val);
}.observes('numericValue')
});
In your template, use the component:
{{numeric-input type="range" numericValue=myValue min="0" max="100"}}
See the following jsbin: http://jsbin.com/vuhunesovono/1/edit?html,js,output