Knockout - observableArray - sans templates - with adding, afterkeydown, and sorting
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.0.0rc.js"></script>
<p>Products:</p>
<select multiple="multiple" height="5" data-bind="options:products, selectedOptions:selectedProducts"> </select>
<div>
<button data-bind="click: removeSelected, enable: productsAreSelected ">Remove</button>
<button data-bind="click: sortProducts, enable: productsExist">Sort</button>
</div>
<form data-bind="submit:addItem">
Add item: <input type="text" data-bind='value:itemToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
</form>
CSS
body{
margin: 20px;
}
select {
width: 150px;
}
JavaScript
var viewmodel = function() {
this.itemToAdd = new ko.observable("");
this.products = new ko.observableArray(["Guitars", "Capos", "Straps", "Picks"]);
this.selectedProducts = new ko.observableArray([]);
this.addItem = function() {
// Prevent blanks and duplicates
if ((this.itemToAdd() !== "") && (this.products.indexOf(this.itemToAdd()) < 0)) {
this.products.push(this.itemToAdd());
}
this.itemToAdd("");
};
this.productsExist = ko.computed(function() {
return this.products().length > 0;
}, this);
this.productsAreSelected = ko.computed(function() {
return this.selectedProducts().length > 0;
}, this);
this.sortProducts = function() {
this.products.sort();
};
this.removeSelected = function() {
this.products.removeAll(this.selectedProducts());
this.selectedProducts([]);
};
};
ko.applyBindings(new viewmodel());