Bindings Computed Property in Ember TextField

我的梦境 提交于 2019-12-21 12:07:20

问题


I'm trying to bind my data model to the text field in Ember.js. The model has a field that represents a currency value (e.g., $1,000.50). The user can then change this value.

Ember receives the data as a Number (1000.50) -not currency formatted. I bind the view to a computed property that has the nice format. Here is my Handlebars template.

{{input classNames="amount" valueBinding="p.amountFmt"}}</td>

My model looks like:

App.Product = Ember.Object.extend({
  amount : 0.00,
  amountFmt: function () {
    //example. Do actual formatting with this.get('amount'); 
    var formattedNum = '1,000.50'; 
    return formattedNum;
  }.property('amount')
});

The problem is, when the user changes the amount in the input field, the underlying 'amount' property on my model is not updated -I suppose because it's bound to the computed property.

What is the correct way to take the user's input, parse and validate if necessary, and store it in the 'amount' property? Should I use bindings/observers between the two properties? How would this work?

Ultimately, the 'amount' property is what get's persisted server side. I really just consider the computed property a place to do UI formatting. I would normally use a Handlebars helper for this kind of formatting but you can't combined the TextField's valueBinding with the results of a Handlebars helper.

Thanks in advance for your help! Andrew


回答1:


The function for the computed property amountFmt acts as both a getter and setter depending on the context. It's signature is amountFmt(key, [value]). The value is optional and only passed in when the value is to be changed.

amountFmt: function(key, value) {
  if (value) {
    // setter
  } else {
    // getter
  }
}.property('amount')


来源:https://stackoverflow.com/questions/17374203/bindings-computed-property-in-ember-textfield

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