Knockout Array Binding
by nwinkler
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.debug.js"></script>
<h3>Items</h3>
<ul id='items' data-bind='foreach: items'>
<li>
<span data-bind='text: name'></span> <span data-bind='text: value'></span> <a href='#' data-bind='click: $parent.updateItem'>Update</a>
</li>
</ul>
<button data-bind='click: addItem'>Add</button>
JavaScript
function Item(name, value) {
this.name = ko.observable(name);
this.value = ko.observable(value);
}
var viewModel = {
items: ko.observableArray([
new Item('EUR', '1.534'),
new Item('GBP', '1.834')
]),
addItem: function() {
this.items.push(new Item('Dummy', '2.455' ));
},
updateItem: function(data) {
var found = ko.utils.arrayFirst(viewModel.items(), function(item) {
return item.name === data.name;
});
found.value('2.222');
}
};
ko.applyBindings(viewModel);