数据绑定:模型对象的属性从整数变为字符串 [英] Data binding: property of model object changes from integer to string

查看:116
本文介绍了数据绑定:模型对象的属性从整数变为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,创建了一个具有属性 foo 的模型对象 myModelObject 最初 foo 设置为一个整数。

修改 foo 在这个表单字段中,以 foo 更改为一个字符串的其他整数结果。





有没有办法确保属性在被保留后保持整数通过表单字段修改



注意: App.myModelObject.set(foo,23) code> foo 保持整数。



我使用Ember 1.7.0。

解决方案

首先,< input type =range> control的属性是一个字符串。要引用 W3C wiki


范围状态表示将元素的值设置为表示数字的字符串的控件。



$ 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: http://jsbin.com/vuhunesovono/1/edit?html,js,output


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.

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:

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

这篇关于数据绑定:模型对象的属性从整数变为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆