Search code examples
javascriptknockout.jsko.observablearray

Knockout doesn't remove items from observable array


I have an observable array that contains a nested tree array. Every array item has a children property which holds his children entries. When I click on the checkbox I would like to remove the ticked table rows which in turn should also remove the rows which shows the children of the selected item. How can I do this? I have a little example on jsFiddle here

this is my knockout template:

<script id="nodeTmpl" type="text/html">
    <tr>
        <td>
            <input type="checkbox" name="check[]" />
        </td>
        <td data-bind="text: name"></td>
    </tr>
    <!-- ko template: { name: 'nodeTmpl', foreach: nodes } --><!-- /ko -->
</script>

I have to use a table instead of a ul because I'm using bootstrap and so I styled it. Also, I have multiple columns and style divs or ul would not makes sense


Solution

  • Here's one solution. Since you have a tree structure, every node has a parent with a nodes array (if we also rename root to nodes). With Knockout, you can always access the parent object using $parent and thus access the enclosing array using $parent.nodes.

    <input type="checkbox"
         data-bind="click: function() { $parent.nodes.remove($data); }" />
    

    JsFiddle: http://jsfiddle.net/mbest/5qqWn/3/