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
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
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"
add
function as part of your view model? It has a dependency on vm existing in the global namespace right now. Instead you could insert the function as an additional property when defining vm
as in this fiddle. Then, you can even interact with the function through binding as well as in this fiddle(great answer btw, I +1'd you) –
Neumark 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.
© 2022 - 2024 — McMap. All rights reserved.