I am facing an issue in knockout js and couldn't find any solution to it, I have a list of objects which I place in an observable array and display them in a table, clicking on a row, populates the object attributes in appropriate fields.
When any field data is updated, it is immediately reflected in table but I want than when I click on Save button than the data must be updated in table so that I can also update that data in database through ajax. A simple fiddle is created at: jsfiddle
Javascript is as:
var myData = [{'Id':1,'UserName':'Imran',Active:true},{'Id':2,'UserName':'Khan',Active:false},{'Id':3,'UserName':'Balouch',Active:true}];
function User(id,name,active)
{
this.Id = ko.observable(id);
this.UserName = ko.observable(name);
this.Active = ko.observable(active);
}
var viewModel = function () {
var self = this;
self.AllUsers = ko.observableArray([]);
self.CurrentUser = ko.observable(new User(-1,'',false));
var mappedUsers = $.map(myData, function (item) {
return new User(item.Id, item.UserName, item.Active);
});
self.AllUsers(mappedUsers);
self.GetUser = function(item)
{
ko.utils.arrayForEach(self.AllUsers(), function (mainItem) {
if (item.Id == mainItem.Id)
self.CurrentUser(mainItem);
});
};
// I want this function to update the table and also send Ajax call.
self.UpdateRecord = function()
{
//ko.utils.arrayForEach(self.AllUsers(), function (mainItem) {
// if (self.CurrentUser().Id() == mainItem.Id())
// mainItem.UserName = self.CurrentUser().UserName();
//});
};
};
$(function () {
ko.applyBindings(new viewModel());
});
and the html is as:
<table style="width:100%;">
<tbody data-bind="foreach:AllUsers">
<tr data-bind="click:$root.GetUser">
<td data-bind="text:Id"></td>
<td data-bind="text:UserName"></td>
<td data-bind="text:Active"></td>
</tr>
</tbody>
</table>
<br/>
<input type="text" data-bind="value:CurrentUser().UserName"/>
<br/>
<button data-bind="click:UpdateRecord">Save</button>
Any help will be appreciated, thanks in advance