Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add/insert an item into an ObservableArray at a certain position with Knockout.js

All the knockout examples I have found seem to add a new item to the end of an ObservableArray using something like:

viewModel.SomeItems.push(someNewItem); 

This of course places the item at the end of the array.

How to I add an item to the ObservableArray at a certain position?

eg. something like:

viewModel.SomeItems.push(someNewItem, indexToInsertItAt); 
like image 591
Mark Robinson Avatar asked Sep 06 '11 09:09

Mark Robinson


People also ask

How do you update items in observableArray knockout?

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).

What is Ko applyBindings?

ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.


Video Answer


2 Answers

You should be able to use the native JavaScript splice method -

viewModel.SomeItems.splice(2,0,someNewItem); 

Docs here - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice

Example here (not Knockout specific) - How to insert an item into an array at a specific index?

From the Knockout docs -

For functions that modify the contents of the array, such as push and splice, KO’s methods automatically trigger the dependency tracking mechanism so that all registered listeners are notified of the change, and your UI is automatically updated.

like image 115
ipr101 Avatar answered Sep 30 '22 05:09

ipr101


For knockout use

viewModel.SomeItems.unshift(someNewItem); 

See also: http://knockoutjs.com/documentation/observableArrays.html

like image 21
Travis Cavanaugh Avatar answered Sep 30 '22 04:09

Travis Cavanaugh