Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i insert element in knockout array at specific index

how do i insert element in knockout array at specific index

I understand we have to use slice and push, but what is the best way and how to insert new element at specific position in observable array

like image 851
ritzy Avatar asked Apr 16 '14 19:04

ritzy


People also ask

What is ObservableArray?

ObservableArray is an array that allows listeners to track changes when they occur. In order to track changes, the internal array is encapsulated and there is no direct access available from the outside. Bulk operations are supported but they always do a copy of the data range.

Which function is used to search or sort an observable array?

The KnockoutJS Observable sort() method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse() method on sorted array.


2 Answers

Use splice. The docs aren't real clear on this (I had to double check it myself), but you can use this just like the regular javascript .splice to insert elements as well as remove them. For example:

var vm = {
    array : ko.observableArray(["foo","bar"])
};

ko.applyBindings(vm);

function Add() {
    vm.array.splice(1,0,"ra");    // at index 1 - remove 0 elements and add "ra"
}

Add();   // "ra" gets inserted between "foo" and "bar"

http://jsfiddle.net/aL4D6/

like image 163
Matt Burland Avatar answered Oct 02 '22 04:10

Matt Burland


I you can do it normally with splice (no reasons for slice and push, because splice can actually do this). Just put you starting position and then 0 to specify that you actually do not want to remove an item, and only add.

var ViewModel = function() {
    this.list = ko.observableArray([1, 2, 3, 5]);
};
vm = new ViewModel();
ko.applyBindings(vm);

So if you then do something like

vm.list.splice(3,0, 'new element');

it will insert it at specific location in the array. Surely you can put this code inside of the model and bind it to some event.

like image 38
Salvador Dali Avatar answered Oct 02 '22 04:10

Salvador Dali