Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding item to observableArray not updating view on jQuery button click

I'm trying to work out why the following example doesn't work.

The observableArray isn't updated until it is manually told that it has changed (using valueHasMutated() ).

I thought the whole point of the observables was that when it changed the view is automatically updated.

<button type='button' id='add'>add</button>
<button type='button' id='mutated'>force update</button>
<div id="short_tasks" data-bind="foreach: list">
  <div data-bind="text: title"></div>
</div>

JS:

var ListTest = function () {

  this.list = ko.observableArray([{title: 'item1'}]);
}

var viewModel = new ListTest();
ko.applyBindings(viewModel);

$('#add').click(function () {
  viewModel.list().push({title: 'new item'});
});

$('#mutated').click(function() {
  viewModel.list.valueHasMutated();
});

jsFiddle: http://jsfiddle.net/InsaneWookie/HFgbR/

like image 582
Rowan Avatar asked Jan 06 '13 03:01

Rowan


1 Answers

You will want to call push directly on the observableArray, which will push your item to the underlying array and notify any subscribers.

viewModel.list.push({title: 'new item'});
like image 107
RP Niemeyer Avatar answered Sep 18 '22 04:09

RP Niemeyer