Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bindings Computed Property in Ember TextField

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

like image 425
anschoewe Avatar asked Jun 28 '13 21:06

anschoewe


1 Answers

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')
like image 174
Darshan Sawardekar Avatar answered Nov 15 '22 19:11

Darshan Sawardekar