davy
davy

Reputation: 4562

Knockout template will not update list when adding to observable array

I have a knockout template:

<script type="text/javascript" id="myList">        
  // template stuff here                   
</script>

I call it in with the foreach option:

<div data-bind="template: { name:'myList', foreach: ItemList }"></div>

I get the view model form my controller and use the following Javascript to bind it:

var viewModel = ko.mapping.fromJS(@Html.Raw(JsonConvert.SerializeObject(Model));                                        
ko.applyBindings(viewModel, document.getElementById("contentsDetails"));

I return a few items from my controller and everything renders fine.

My problem is that if I add to my observable array

var itemToAdd = {
            Name:  ko.observable("name a"),
            Desc:  ko.observable("desc a")
 }

 viewModel.MyObservableArray().push(itemToAdd);

I have checked the array is observable using:

 console.log(ko.isObservable(viewModel.MyObservableArray));

It does not update the UI template by adding the new item to the list.

What am I doing wrong here?

Upvotes: 1

Views: 1217

Answers (1)

James Thorpe
James Thorpe

Reputation: 32212

It's this line:

viewModel.MyObservableArray().push(itemToAdd);

By putting brackets after MyObservableArray, you're accessing the underlying array, and directly pushing the value into it. Knockout doesn't see this change. Instead, call .push directly on the observableArray:

viewModel.MyObservableArray.push(itemToAdd);

This is a method in knockout that will update the underlying array and notify any subscribers of the change, and will result in the UI being updated.

Alternatively, you can keep it as you have it, but inform knockout that it has changed, which will trigger the updates:

viewModel.MyObservableArray().push(itemToAdd);
viewModel.MyObservableArray.valueHasMutated();

Upvotes: 9

Related Questions