问题描述
在我的应用程序中,创建了一个具有属性
修改 foo 在这个表单字段中,以 foo 更改为一个字符串的其他整数结果。
- 示例w / o Ember数据:
- 使用Ember数据的示例:
有没有办法确保属性在被保留后保持整数通过表单字段修改
注意: App.myModelObject.set(foo,23) code> foo 保持整数。
我使用Ember 1.7.0。
首先,< input type =range> control的值属性是一个字符串。要引用:
$ b $我不相信你会超过浏览器的基本限制。
其次,你的问题是关于如何将该值强制为数。你可以这样做:
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')
});
在您的模板中,使用组件:
{{numeric-input type =rangenumericValue = myValue min =0max =100}}
请参阅以下jsbin:
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.
First of all, the <input type="range"> control's value property is a string. To quote the W3C wiki:
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
这篇关于数据绑定:模型对象的属性从整数变为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!