In my previous post, we saw how to add items in a SP list using KO. This post will focus on removing items from a list. The code snippet at the end combines all the three posts. Using it; you can display, add and remove items from list. Besides that we send only updated (i.e. added or removed) data to server side. Going on the same lines, we can implement the “edit” functionality also. Right now, I am skipping it.
For reference, the other two posts are:
- Part I – Displaying Data from SP list.
- Part II – Adding Data to SP list.
- Part III – Removing Data from SP list. (this one)
To add remove functionality, a “Remove this” link is added after every row in the table. So, the html looks like:
$root.RemoveCountries will update the view model. Here $root is the main view model in the topmost/parent context. It will update the whole table by removing the current row.
“Id” column of sharepoint list is also included in the “CountryList” class to delete items by id. For newly created rows the id is assigned to ‘0’. After every update to the server, the “changedCountries” array is emptied.
The final result will look like,
Now, the final collaborated code is:
Summary: KO is an amazing library that makes life easier by segregating the display logic with the business logic. Using it in SP, makes the js code neat and simple to understand. The only flip side is, if there are changes at the server side, then UI is not automatically updated until a refresh is performed. Regardless of this, KO is a library we all should learn.
P.S.: This example is by no means perfect or bug free. There are few loopholes like:
- User can edit the existing items but this is not handled in the code.
- After adding a new item to SP list the view model is not updated unless user do a refresh.
- Only 20 items are fetched and no pagination is implemented.
But the code is for demo purpose only. You can extend it in any way you want. Hope it helps!!
Another good blogs on KO (also referenced here):
- Knockout.js Simplified
- Using Knockout.js in a sharepoint context