Ember TextField valueBinding与动态属性 [英] Ember TextField valueBinding with dynamic property

查看:71
本文介绍了Ember TextField valueBinding与动态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个通用视图来处理我的应用程序中的自定义字段,但是我很难让它工作。这是场景 - 我有一个定义了自定义字段的 fieldDef 对象,还有一个 valueObject ,它有一个数组, code> customFields ,具有值。我想要做的是这样的:

I'm trying to write a generic view that handles custom fields in my app, but I'm having a hard time getting this to work. Here's the scenario - I have a fieldDef object which defines the custom fields, and a valueObject which has an array, customFields, which has the values. What I'm trying to do is something like this:

{{view Ember.TextField valueBinding="valueObject.customFields.[fieldDef.name]"}}

显然这不起作用,因为它处理 fieldDef.name 作为文字。我尝试覆盖TextField类,但似乎无法让它绑定。

Obviously that doesn't work because it treats fieldDef.name as a literal. I've tried overriding the TextField class, but can't seem to get it to bind.

有关如何实现这一点的任何建议?

Any suggestions on how to accomplish this?

谢谢,
Scott

Thanks, Scott

推荐答案

t绑定到数组索引,所以你必须解决它。一个解决方案是将自己限制为单向绑定,其中您的文本字段更新值哈希。如果您打算在用户按下按钮后提交表单,那么应该做到这一点。

Ember can't bind to an array index, so you'll have to work around it. One solution is to limit yourself to a one-way binding, where your textfield updates the values hash. If you're planning to submit the form after the user presses a button, this should do the trick.

在控制器中定义一个字段ID数组,他们的值进去。

Define an array of field ids in your controller and a hash for their values to go in.

App.ApplicationController = Ember.Controller.extend({
  fieldIds: ['name', 'email', 'whatever'],
  fieldValues: {} // {name: 'user', email: 'user@...', ...}
});

现在扩展 Ember.TextField 更新您的当文本字段更改时,值为散列值。你需要传递每个实例一个 fieldId ,并从控制器引用哈希。

Now extend Ember.TextField to update your values hash when a text field changes. You'll need to pass each instance a fieldId and a reference to the values hash from your controller.

App.TextField = Ember.TextField.extend({
  fieldId: null,
  values: null,

  valueChange: function() {
      var fieldId = this.get('fieldId');
      var values = this.get('values');
      if (values && fieldId) values[fieldId] = this.get('value');
  }.observes('value')
});

模板很简单。

{{#each fieldId in fieldIds}}
  <label>{{fieldId}}</label>
  {{view App.TextField fieldIdBinding="fieldId" valuesBinding="fieldValues"}}
  <br/>
{{/each}}

这里是一个jsfiddle

这篇关于Ember TextField valueBinding与动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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