我有一个组件接受一个值数组和相同长度的数组,每个值都有一个验证错误字符串.我想显示一个表单字段列表,其中包含每个值和错误对的输入.我试过像这样创建一个计算属性:
var myComponent = Ember.Component.extend({
//values: <provided array of input values>
//errors: <provided array of error strings>
valuesAndErrors: function() {
var combined = [];
for (var i = 0; i < values.length; i++) {
combined.pushObject({
value: this.get('values')[i],
error: this.get('errors')[i]
});
}
return combined;
}.property('values.@each', 'errors.@each')
});
Run Code Online (Sandbox Code Playgroud)
但不幸的是,对valuesAndErrors(例如via {{input value=valuesAndErrors.value}})中的值所做的更改不会被推回源values数组.在不破坏这样的绑定的情况下values,errors同时迭代和数组的正确方法是什么?
我目前正在使用Ember 1.9.
为什么不在控制器中使用一个计算属性来组合两者,然后将其传递到组件中,而不是为 和 传递单独的数组values?errors
所以,你的控制器可能看起来像这样:
App.ApplicationController = Ember.Controller.extend({
values: function(){
return ["one", "two", "three"];
}.property(),
errors: function(){
return ["oneError", "twoError", "threeError"];
}.property(),
valuesAndErrors: function() {
var combined = [];
var values = this.get('values');
var errors = this.get('errors');
values.forEach(function(value, index){
combined.pushObject({
value: value,
error: errors[index]
});
});
return combined;
}.property('values.@each', 'errors.@each')
});
Run Code Online (Sandbox Code Playgroud)
还有你的组件模板(你甚至不需要任何组件 JS 就可以工作):
<script type="text/x-handlebars" id='components/value-error'>
<h2>Inside of Component</h2>
{{#each item in valuesAndErrors }}
{{ input value=item.value }} - {{ input value=item.error }}<p/>
{{/each}}
</script>
Run Code Online (Sandbox Code Playgroud)
工作示例在这里
更新

| 归档时间: |
|
| 查看次数: |
663 次 |
| 最近记录: |