简体   繁体   中英

aurelia and recursive binding

Consider the following data:

[
{
 "id": 1,
 "text": "I am parent",
 "children": [
  {
    "id": 2,
    "text": "I am child",
    "parentId": 1,
    "children": [
      {
        "id": 4,
        "text": "I am a grand child",
        "parentId": 2,
        "children": null
      },
      {
        "id": 5,
        "text": "I too am a grand child",
        "parentId": 2
      }
    ]
  }
]
}
]

And the corresponding component for each entry above is called menu-item. The html is as follows:

<template>
  <ul class="menu-item-list" show.bind="expanded">
    <li class="" repeat.for="child of menu.children">
      <menu-item menu.bind="child"></menu-item>
    </li>
  </ul>
</template>

Note that menu-item renders itself recursively for each of the menu item's children. Up to this point, everything works great. Aurelia renders the root menu and all the child menus recursively. The problem is when I attempt to add a menu item to the existing list. I have a button which prompts the user for a menu text, and inserts it as the child of whatever menu is selected. For instance, if I have selected the item with id = 2, it is supposed to insert the new entry as the child of menu item 2. And although the viewmodel is updated, (the debugger very clearly shows that the model is changing, and the newly added item is there), the view is not . If I click on another page and come back to this page, then I can see the item I just added. I have tried everything I can think of, the signaler, the event aggregator, creating a getter on the children array. No matter what I do, the view does not reflect the changes in the children array. What am I doing wrong? What am I missing?

Thanks for the help!

UPDATE

Plunk added.

This was a tricky one- the issue is hasChildren and expanded are not updated on the menu element after a child has been pushed into the data structure.

Here's a plunker that removes the hasChildren check and the expanded check just to demonstrate that your main logic is working properly, just needs a few tweaks.

http://plnkr.co/edit/n0RFaeS5wr9EpbkrrBbX?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM