Simple Items List

working ko,observableArray, push, pop, removeAll and Sort methods

by Diya_Khan

HTML

<div>
    New Item 
    <input type="text" data-bind="value:itemToAdd, valueUpdate : 'afterkeydown'" />
    <button data-bind="click: addItem , enable:itemToAdd().length > 0" type="submit">Add</button>    
</div>

<div>
    List Items
    <select data-bind="options : items, selectedOptions: selectedItems" multiple="multiple" ></select>
    <button data-bind="click: removeItems">Remove </button>
</div>

<div>
    <button data-bind="click: sortItems">Sort</button>
</div>

CSS

select
{
    height: 100%;
    width: 30%;
}

JavaScript

var itemsDataModel = function(items){
    this.items = ko.observableArray(items);
    this.itemToAdd = ko.observable("");
    this.selectedItems= ko.observableArray(["A"]);
    this.addItem = function(){
        if(this.itemToAdd() != "")
        {
        this.items.push(this.itemToAdd()); //"push" insert new item in list
        this.itemToAdd("");
        
        }
        
        }.bind(this);
    
    this.removeItems = function() {
        this.items.removeAll(this.selectedItems());
        this.selectedItems([]); // Clear selection
        }.bind(this);

    this.sortItems = function(){
        this.items.sort();
    };
};

    

ko.applyBindings(new itemsDataModel(["A","B","C"]));