Search code examples
javascriptif-statementknockout.jsconditional-statementsvisible

knockout conditional binding weird behavior


I wanted to display missed call icon on getting a missed call , so for that i am maintaining a list of missed call received and i am comparing it with the current ID like shown below

<div class="col m1" data-bind="visible:$component.missedCallList().indexOf($data._id)>=0">
   <img src="${require(`./../../../../icons/icon-missed-call.svg`)}" alt="" class="responsive-img _badges">
 </div>

But the visibility isnt toggling when the list is updated or empty.
so on a certain event i am removing the entry like

removeFromList(index){
  if (index >= 0) {
            this.missedCallList().splice(index, 1)
        }
}

But it isnt updating on the UI.


Solution

  • You don't need the () when you call splice. Instead call splice directly on the observable array.

    e.g.

    missedCallList.splice(index, 1)
    

    Also in your code this might be referring to the remove function when it should probably be referring to the parent missedCallList property. You can set this to another variable in the parent scope and access that from within the function.

    e.g.

    var self = this;
    
    function removeFromList(index) {
      if (index >= 0) {
        self.missedCallList.splice(index, 1);
      }
    }