allencoded
allencoded

Reputation: 7275

Re-Run bind() or attached() after data changes where repeat.for is used

I want to be able to change my data and have it re-run the repeat.for child element class function bind(). Because I need to be able to change data in the parent and have the child re-draw properly.

So in short I want to change data in parent.js after repeat.for has occurred. Which I want the child to reflect the correct template afterwards by re-running bind().

Parent.html:

<template>
  <button click.trigger="changeData()">test</button>
  <li class="event-item eb-item-created" repeat.for="d of data">
    <child data.two-way="d"></child>
  </li>
</template>

Child.html

<template>
  <require from="./task/text/text"></require>
  <require from="./task/mcma/mcma"></require>
  <require from="./task/grid/grid"></require>

  <text containerless if.bind="text" data.two-way="data"></text>
  <mcma containerless if.bind="mcma" data.two-way="data"></mcma>
  <grid containerless if.bind="grid" data.two-way="data"></grid>
</template>

Child.js:

  ...
      bind() {
        this.getDataType(); // calls a switch to grab data.type 
      }

    getDataType() {
      switch (this.data.type) {
        case 'text':
          this.text = true;
          break;
...

Upvotes: 0

Views: 111

Answers (1)

Jeremy Danyow
Jeremy Danyow

Reputation: 26406

change child.js from this:

@bindable data;

bind() {
  this.getDataType(); // calls a switch to grab data.type 
}

getDataType() {
  switch (this.data.type) {
    case 'text':
      this.text = true;
      break;
    ...
  }
  ...

to this:

@bindable data;

dataChanged(newValue, oldValue) {
  switch (this.data.type) {
    case 'text':
      this.text = true;
      break;
    ...
  }
  ...
}

Aurelia will automatically call a method on your view-model when a @bindable property changes as long as the method's name matches the @bindable property's name plus the word Changed.

You might also consider removing all that logic in your view model binding directly to the type property:

<text containerless if.bind="data.type === 'text'" data.bind="data"></text>
<mcma containerless if.bind="data.type === 'mcma'" data.bind="data"></mcma>
<grid containerless if.bind="data.type === 'grid'" data.bind="data"></grid>

Upvotes: 1

Related Questions