Reputation: 527
I am using the Knockout JS, I have a delete function which is working, but my UI is not updating with deletions, it displays the item which has been deleted, Even in my DB, the data has been deleted, How do I fix this? code:
function UserViewModel()
{
var self=this;
self.UserProfile = ko.observableArray([]);
//Get user all details
self.GetUserDetails=function(){
$.ajax({
type: "POST",
dataType: "json",
data: Model,
url: serverUrl + 'api/controller/Action',
success: function (data) {
var UserDetailsmappedData = $.map(data, function (item) {
return new userModel(item);
});
self.UserProfile (self.UserProfile ().concat(UserDetailsmappedData));
},
})
}
//Delete Profile
self.DeleteUserProfile = function (UserProfile)
{
var ProfilestatusID = (UserProfile.UserProfileID())
console.log(ProfilestatusID)
Model = { userID: ProfilestatusID }
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
data: Model,
url: serverUrl + 'api/controller/Action',
success: function (data) {
self.GetUserDetails();
},
}) }
//My Model
function userModel(data){
self.userId=ko.observable(data.userID);
self.userName=ko.observable(data.userName);
self.userImage=ko.observable(data.userImage)
}
$(document).ready(function () {
viewModel=new UserViewModel();
ko.applybindings(viewModel)
});
Upvotes: 0
Views: 431
Reputation: 83
After delete you should remove the deleted items from the observable array self.UserProfile
, here self.UserProfile(self.UserProfile().concat(UserDetailsmappedData));
seems that you are concatenating the results to the existing array
Upvotes: 0
Reputation: 1020
The user profile you deleted never gets removed from the observablearray because the old array always gets merged with the updated one after the GetUserDetails() call.
Best thing would be if you just remove the user profile from the array in the success callback instead of calling GetUserDetails() again. So:
$.ajax({
type: "POST",
dataType: "json",
data: Model,
url: serverUrl + 'api/controller/Action',
success: function (data) {
self.UserProfile.remove(UserProfile); //DB is already updated, no
//need to call
// GetUserDetails() again
},
}) }
Or if you want to keep the deleted items in your array for whatever reason, just update the UserProfile, eg:
UserProfile.deleted(true)
Upvotes: 1