Ember TextField valueBinding 与动态属性 [英] Ember TextField valueBinding with dynamic property
问题描述
我正在尝试编写一个通用视图来处理我的应用程序中的自定义字段,但我很难让它发挥作用.这是场景 - 我有一个 fieldDef
对象,它定义了自定义字段,还有一个 valueObject
对象,它有一个数组,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?
谢谢,斯科特
推荐答案
Ember 无法绑定到数组索引,因此您必须解决它.一种解决方案是将自己限制为单向绑定,其中您的文本字段更新值哈希.如果您打算在用户按下按钮后提交表单,这应该可以解决问题.
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
和对来自控制器的 values
哈希的引用.
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}}
这篇关于Ember TextField valueBinding 与动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!