0
votes

I have an observableArray of posts. Each post should have its observableArray of comments, which i'm doing this way:

self.posts.subscribe(posts) {
 ko.utils.arrayForEach(posts, function(post) {
  post.comments = ko.observableArray()
 })
}

So I have two foreachs:

<!-- ko foreach: posts -->
 <div class="post">
 ...
  <!-- ko forech: comments -->
   <div class="comment">
    <span class="delete_comment" data-bind="click: $root.deleteComment"></span>
   </div>
 <!-- /ko -->
<!-- /ko -->

In my viewmodel, the deleteComment function:

self.deleteComment = function(comment) {
//ajax..
// now i should remove this comment from the comments array
}

The problem here is that I just can't find a way to remove the comment from the comments array. I can't access the comments array from the viewmodel since it's dynamically created. I tried to bind the parent in the data-bind:

<span class="delete_comment" data-bind="click: $root.deleteComment.bind($parent)"></span>

But there's no difference, the first argument in deleteComment is still the comment object. How can I access the outer observableArray from inside deleteComment?

1

1 Answers

0
votes

But there's no difference, the first argument in deleteComment is still the comment object.

Your bind changed what this is in the deleteComment function, not what the first argument is. If you don't need this for something else in deleteComment, you're good to go — use this.comments.


Or, of course, make the posts responsible for deleting their comments, rather than the root model.