我该如何获得此输入字段的值?

时间:2015-02-27 10:38:55

标签: ember.js ember-cli

我在{{input value=(cents-to-dollars model.amountInCents)}}使用子表达式。它使用自定义帮助器将值从美分转换为美元。我的API返回美分。

但是,在控制器save操作中,console.log(this.get('model.amountInCents'));会返回undefined。我错过了什么吗?输入帮助器中可能是namevalueBinding吗?

如果我删除子表达式。 console.log(this.get('model.amountInCents'));输出正常。

// Routes
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('product', params.product_id);
  }
});

// Controller
export default Ember.Controller.extend({
  actions: {
    save: function() {
      console.log(this.get('model.amountInCents')); // returns undefined
      var _this         = this;
      var dollars       = this.get('model.amountInCents');
      var amountInCents = dollars / 100;

      this.get('model').set('amountInCents', amountInCents);

      this.get('model').save().then(function(product){
        _this.transitionToRoute('admin.products.show', product);
      }, function() {
        // Need this promise, so we can render errors, if any, in the form
      });

      return false;
    },
    cancel: function() {
      this.transitionToRoute('products.show', this.get('model'));
    }
  }
});

// Template
<form {{action "save" on="submit"}}>
  <p>
    <label>Name:
      {{input value=model.name}}
    </label>
  </p>

  <p>
    <label>Amount in cents:
      {{input value=(cents-to-dollars model.amountInCents)}}
    </label>
  </p>

  <input type="submit" value="Save"/>
  <button {{action "cancel"}}>Cancel</button>
</form>

1 个答案:

答案 0 :(得分:2)

首先,(至少在版本1.9.1中)你提议的内容并不真正有用(参见here - 值出现在输入字段之外)。我认为,真正的问题是你没有绑定到属性,而是绑定到从帮助器返回的字符串(这不是你想要的)。

那么,你能做什么?

您可以按如下方式设置dollars计算属性:

App.IndexController = Ember.ObjectController.extend({
  dollars: function(key, value){
    if (arguments.length > 1) {
      var dollars = value;
      this.set('amountInCents', parseInt(dollars) * 100);
    }

    return this.get('amountInCents') / 100;
  }.property('model.amountInCents')
});

完整的工作示例here