0
votes

I have an ObservableArray of objects which users can remove from. When an object is removed, the object is deleted from the UI, and this calls a function on the back end that removes an object at that index in a list that is attached to my model, and then naturally, the list resizes. However, on the front end, the observable array is not resizing. If I remove an item in the third position, at index 2, then click to remove an item in that same position, it will make a call to remove the item at index 3, since the observable array has not been resized. Is there a way to make this array resize every time, or move everything to the proper position, without recreating the observable array every time an object is removed?

The code for the ViewModel and remove is

    function TweetViewModel(){
    var self = this;
    self.tweets = ko.observableArray([]);
    self.removeTweet = function(tweet) {
    self.tweets.remove(tweet);
   };
  }
1

1 Answers

3
votes

Don't see any issue with your code as it's shown.

See this working JSFiddle, that may highlight something you are missing.

HTML

<div data-bind="foreach: tweets"> 
    <span data-bind="text: $data"></span>
    <input type="button" data-bind="click: $root.removeTweet" value="remove" />
    <hr/>
</div>

View Model

function TweetViewModel(){
    var self = this;
    self.tweets = ko.observableArray(['one','two','three']);
    self.removeTweet = function(tweet) {
    self.tweets.remove(tweet);
   }       
}
ko.applyBindings(new TweetViewModel());