Marcus Renno Marcus Renno - 2 months ago 22
Javascript Question

Bind checkbox to element of one array in Ember 2+

I'm trying to bind elements of one array to the checked attribute of checkboxes using Ember 2.8. I'm also using this in one component.

The checkboxes show all marked, but whenever I tried to use the action

hideOrShowAllColumns
it does not mark all checkboxes again if there was one which was not checked... so I guess I'm passing the value of the array element and not the element itself. I don't know how to do this in javascript/ember...

This is my view

{{input type="checkbox" name="all" checked=allColumnsChecked change=(action "hideOrShowAllColumns")}}
All
{{#each model_table.columns as |column index|}}
{{input type="checkbox" name=column checked=(getItemAt allColumns index) change=(action "hideOrShowColumn" index)}}
{{column}}
{{/each}}


This is my component.js

export default Ember.Component.extend({
init() {
this._super(...arguments);
this.set('allColumnsChecked', true);
},
didReceiveAttrs() {
this._super(...arguments);
let columnMap = this.get('columnMap');
let allColumns = Array(columnMap.length).fill(true);
this.set('allColumns', allColumns);
},
actions: {
hideOrShowAllColumns() {
let all = this.get('allColumnsChecked');
all = !all;
this.set('allColumnsChecked', all);
if (all === true) {
let allColumns = this.get('allColumns');
allColumns = allColumns.map(() => true);
this.set('allColumns', allColumns);
}
},
}


Helper getItemAt

export function getItemAt(params) {
return params[0][params[1]];
}

Answer

For two-way binding you can't use primitive type.checked=(getItemAt allColumns index) this part won't workout. it will not update allColumns array values when you checked checkbox.
So I would recommend you to have model_table.columns in this array of column you can have checked property and you can use it in input helper.

First, model_table.columns should be an array of objects.

model_table.columns = [
    {
       'name': 'foo',
       'checked': true
    },
    {
       'name': 'bar',
       'checked': true
    }
]  

Second, use the property in the htmlbar

{{#each model_table.columns as |column index|}}
    {{input type="checkbox" name=column.name checked=column.checked change=(action "hideOrShowColumn" index)}}
    {{column.name}}
{{/each}

Whenever you update checkbox it will update corresponding column.isChecked property.

To update the corresponding column need to use

Ember.set(column, 'checked', true)

where column is one element of the model_table.columns and checked is its property

Comments