remove from array
http://stackoverflow.com/questions/12201010/remove-from-observablearray-knockoutjs
by rniemeyer
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<div>
Name: <span data-bind="text: Name"></span>
</div>
<div>
Items: <button data-bind="click: addItem">Add Item</button>
</div>
<div>
<table>
<tbody data-bind="template: { name: 'itemTemplate', foreach: Items }"></tbody>
</table>
</div>
<button data-bind="click: getJSON">Show JSON</button>
<script type="text/html" id="itemTemplate">
<tr>
<td>
<input data-bind="value: value" />
<a href="#" data-bind="click: $parent.removeItem">Remove Item</a>
</td>
</tr>
</script>
JavaScript
var data = {
Name: "Test",
Items: ["One", "Two", "Three"]
};
function ViewModel(data) {
var self = this;
self.Name = ko.observable(data.Name);
self.Items = ko.observableArray(ko.utils.arrayMap(data.Items, function(item) {
return { value: ko.observable(item) };
}));
self.addItem = function() { self.Items.push({ value: ko.observable("") }); };
self.removeItem = function(data) {
self.Items.remove(data);
};
self.getJSON = function() {
//if the key is a # (array item) and it has value prop, then return it instead
alert(ko.toJSON(self, function(key, value) {
if (!isNaN(key) && value && value.value) {
return value.value;
}
return value;
}, 2));
};
}
$(document).ready(function() {ko.applyBindings(new ViewModel(data)); });