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}?**
2
  • 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: knockoutjs.com/documentation/observableArrays.html Commented Jul 14, 2017 at 8: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. Commented Jul 14, 2017 at 9:06

1 Answer 1

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

-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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.