Costa
Costa

Reputation: 654

Ember.js how to observe array keys changed by input

I have an object with a couple dozens of settings, some settings depend on other settings, so, I need to observe if some setting changed.

import Ember from 'ember';

export default Ember.Controller.extend({
   allPermissionChanged: function () {
      alert('!');
  }.observes('hash.types.[].permissions'),
  permissionsHash: {
    orders:{
      types: [
        {
          label: 'All',
          permissions: {
            view: true,
            edit: false,
            assign: false,
            "delete": false,
            create: true
          }
        },

        }
      ],
      permissions:[
        {
          label:'Просмотр',
          code:'view'
        },
        {
          label:'Редактирование',
          code:'edit'
        },
        {
          label:'Распределение',
          code:'assign'
        },
        {
          label:'Удаление',
          code:'delete'
        },
        {
          label:'Создание',
          code:'create'
        }
      ]
    }
  }

});

Next I try to bind each setting to input

<table class="table table-bordered">
    <thead>
    <tr>

      {{#each hash.types as |type|}}
          <th colspan="2">{{type.label}}</th>
      {{/each}}
    </tr>

    </thead>
    <tbody>
    {{#each hash.permissions as |perm|}}
        <tr>
          {{#each hash.types as |type|}}
            {{#if (eq (mut (get type.permissions perm.code)) null)}}
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            {{else}}
                <td>{{perm.label}}</td>
                <td>{{input type="checkbox"  checked=(mut (get type.permissions perm.code)) }}</td>

            {{/if}}
          {{/each}}
        </tr>
    {{/each}}
    </tbody>

</table>

But observer doesn't work.

Also I prepared Jsbin example - http://emberjs.jsbin.com/havaji/1/edit?html,js,output

Upvotes: 3

Views: 1063

Answers (2)

Karl-Johan Sj&#246;gren
Karl-Johan Sj&#246;gren

Reputation: 17612

You are using the wrong syntax for that. hash.types.[] should only be used if you want to observe an actual array, when something is added or removed from it. To observe a property in an array you you [email protected].

allPermissionChanged: function () {
  alert('!');
}.observes('[email protected]')

You can read more about it in the Ember Guides.

Upvotes: 3

Daniel
Daniel

Reputation: 18692

You could change booleans to objects with boolean property so you could properly observe value of checkbox.

Controller:

App.IndexController = Ember.Controller.extend({
    testData: Ember.ArrayProxy.create({
        content: [
            { value: true },
            { value: false },
            { value: true }
        ]
    }),

    //...

Template:

{{input type='checkbox' checked=data.value}}

Observer:

arrayChanged: Ember.observer('[email protected]', function () {
    console.log('changed');
})

Working demo.

Upvotes: 1

Related Questions