0

I found this question to be similar as mine - Replace all elements in Knockout.js observableArray

I just have another question - if I replace all the elements of observableArray with new contents, will that reflect in the UI as well?

Here's the scenario: I have a html file which displays a table full of contents. Here is my js code snippet which fetches the data bound between js and html-

var table = ko.observableArray(); // {1,2,3,4,5} - UI shows 1,2,3,4,5 in the table
// now I replace all the contents
table = {6,3,8,9};
// **will the UI display the updated content, which is {6,7,8,9} in the table? Or will it still display {1,2,3,4,5}?**
AlwaysALearner
  • 6,320
  • 15
  • 44
  • 59
  • 2
    In your question, the array is observable, its content not. If you change an elment of the array, your UI don't get updated. If you add/remove elements, then the UI is updated. Here is more information: http://knockoutjs.com/documentation/observableArrays.html – Jose Luis Jul 14 '17 at 08:47
  • 1
    Yes. My intent is to remove all contents of the array and put new ones, and make sure the new ones reflect in the UI. – AlwaysALearner Jul 14 '17 at 09:06

1 Answers1

1

Yes since its an observable it will update the UI also. See working example:

https://jsfiddle.net/fkxgk7rc/4/

var data = [1,2,3,4,5];
function viewModel() {
  var self = this;  
  self.myList = ko.observableArray(data); 

  self.addToList = function (listData) {
    for (var i = listData.length; i-- > 0;)
       self.myList.push(listData[i]);
  }

  self.replaceList = function (listData) {
      self.myList(listData);
  }
}
tyler_mitchell
  • 1,727
  • 1
  • 19
  • 27
  • -1 In the OP's example, the value of the var `table` is overwritten and would not update the UI. In your answer and fiddle, the values are injected into the observable and the UI *is* updated. This is an important distinction. If someone simply reads the OP's example and your "Yes", they would come to the wrong conclusion about how this may be done. – claytond Jan 25 '18 at 18:32