Helper with array observer


#1

I am trying to create a helper that is observing an array. When the array changes, I want the helper to reevaluate. I am using the helper in a checkbox input that is created as part of an #each structure. The helper determines the value of checked.

I can’t figure out how to set up the array observer correctly. Here is an Ember Twiddle with a simplification of what I have done.

https://ember-twiddle.com/20c0dba6220858b8395e0a462bd9fb9a?numColumns=2&openFiles=controllers.application.js%2Ctemplates.application.hbs

Thanks for taking a look.

Chris

UPDATE: The twiddle above should now contain a working pattern for multiple checkboxes inside an #each, and with a check-all option, that does not use a model attribute to track the “checked” state.


#2

This is what I have in the helper…

export default Helper.extend({
compute(container, item) {
container.addArrayObserver({
	arrayWillChange() {
    console.log("willChange");
  }
  ,arrayDidChange() {
    console.log("didChange");
  }
});
container.arrayContentWillChange(0);
container.arrayContentDidChange(0);
return container.includes(item);

}


#3

And this is where I’m calling it in the template…

	{{#each model.musketeers as |musketeer|}}
<div>
	<input type="checkbox" checked={{includes checkedItems musketeer}} onChange={{action "toggleSelection" musketeer}}/>{{musketeer.name}}
  </div>
{{/each}}

#4

Okay… My coworker straightened me out:

import Helper from '@ember/component/helper'

export default Helper.extend({
	compute(params) {
    params[0].addArrayObserver(this);
    return params[0].includes(params[1]);
  }
  
  ,arrayDidChange() {
    this.recompute();
  }
  ,arrayWillChange() {}
});