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.asObjects }"></tbody>
    </table>
</div>

<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

<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,
        itemsAsObjects;
    
    self.Name = ko.observable(data.Name);
    
    itemsAsObjects = ko.observableArray(ko.utils.arrayMap(data.Items, function(item) {
        return { value: ko.observable(item) };
    }));
         
    self.Items = ko.computed(function() {
        return ko.utils.arrayMap(itemsAsObjects(), function(item) {
             return item.value();
        });            
    });
    //need to create Items first before attaching this, so we can bind against it
    self.Items.asObjects = itemsAsObjects;
    
    self.Items.asObject =                            
    self.addItem = function() { self.Items.asObjects.push({ value: ko.observable("") }); };
    self.removeItem = function(data) { 
        self.Items.remove(data);
    };
}
$(document).ready(function() {ko.applyBindings(new ViewModel(data)); });