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);
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 :).
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.
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.
For knockout use
viewModel.SomeItems.unshift(someNewItem);
See also: http://knockoutjs.com/documentation/observableArrays.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With