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>

<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 Item(data) {
   this.value = ko.observable(data);  
};

Item.prototype.toJSON = function() {
    return ko.utils.unwrapObservable(this.value);  
};


function ViewModel(data) {
    var self = this;
    self.Name = ko.observable(data.Name);
    self.Items = ko.observableArray(ko.utils.arrayMap(data.Items, function(item) {
        return new Item(item);
    }));
                                    
    self.addItem = function() { self.Items.push(new Item("")); };
    self.removeItem = function(data) { 
        self.Items.remove(data);
    };    
}
$(document).ready(function() {ko.applyBindings(new ViewModel(data)); });