Simple Array Manipulation Using Knockout.js (Add, Remove All, Remove Item, Show)
Most of KnockoutJS features involves binding of a viewmodel object to the a view. But there are special cases where in you want to manipulate ordinary arrays without using ko.observableArray(). So to expound more on this post, here's a sample code below:
KnockoutJS code:
Html markup:
Sample output using console.log() statements from the Knockout array script:
KnockoutJS code:
$(document).ready(function () { function ProductViewModel() { //product array this.Products = [{ id: '1', name: 'Wax' }, { id: '2', name: 'Cotton Buds' }, { id: '3', name: 'Nova' }, { id: '4', name: 'Milo' } ]; //insert product this.Add = function () { console.log('Insert Activity'); this.Products.push({ id: '5', name: 'Test' }); console.log('Total products: ' + this.Products.length); }; //show custom method this.Show = function () { console.log('Display Activity'); console.log('Products in array:'); ko.utils.arrayForEach(this.Products, function (v) { console.log(v.id + ' ' + v.name); }); }; //delete product item this.Delete = function() { console.log('Remove Item Activity'); var product; if (this.Products.length > 0) { ko.utils.arrayForEach(this.Products, function (item) { //remove last item if (item.id == '4') { console.log('Item deleted: ' + item.id + ':' + item.name); product = item; } }); ko.utils.arrayRemoveItem(this.Products, product); console.log('Total products: ' + this.Products.length); } else { alert('No Products to remove!'); } }; //clear array this.DeleteAll = function() { console.log('Remove All Items Activity'); if (this.Products.length > 0) { this.Products = []; console.log('Total products: ' + this.Products.length); } else { alert('No Products to remove!'); } }; } ko.applyBindings(new ProductViewModel()); });
<button data-bind='click: Add'>Add Item</button> <button data-bind='click: Show'>Show Items</button> <button data-bind='click: Delete'>Delete Item</button> <button data-bind='click: DeleteAll'>Delete All Items</button>
Comments
Post a Comment