Iterate over two arrays in time without breaking the binding

I have a component that takes an array of values ​​and an array of the same length with a validation error string for each value. I would like to display a list of form fields with inputs for each pair of values ​​and errors. I tried to create a computed property as follows:

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 ') }); 

But, unfortunately, changes made to values ​​in valuesAndErrors (for example, via {{input value=valuesAndErrors.value}} ) are not returned to the original values array. What is the correct way to iterate arrays of values and errors simultaneously without breaking the bindings like this?

I am currently using Ember 1.9.

+5
source share
1 answer

Instead of passing in a separate array for values and errors , why not calculate the property in the controller that combines the two, and then pass this to the component?

So your controller might look something like this:

 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 ') }); 

And your component template (you don’t even need a JS component for this):

 <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> 

Working example here

UPDATE

enter image description here

+1
source

Source: https://habr.com/ru/post/1211294/


All Articles