Data binding: property of model object changes from integer to string

╄→гoц情女王★ 提交于 2019-12-23 18:26:35

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/25512358/data-binding-property-of-model-object-changes-from-integer-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!