AnkUser
AnkUser

Reputation: 5531

Knockout: Table Select Unselect Row. Issue/challenge with unselecting Row

I have a Table using Knockout to fill in data and to select the rows. The challenge right now is I can select the row and it's details I can see. But when I click on paging or if on any particular search box I wish to deselect the Row.

Here is the Fiddle which will explain More

Below is the Model Code for the HTML Page

var RowModel = function(id, name, status) {
  this.ID = ko.observable(id);
  this.Name = ko.observable(name);
  this.Status = ko.observable(status);

};

RowModel.fromRawDataPoint = function(dataPoint) {
  return new RowModel(dataPoint.id, dataPoint.name, dataPoint.status);
};

Upvotes: 0

Views: 131

Answers (1)

Ray
Ray

Reputation: 3959

From the fiddle, I can see that you are implementing deselect by calling self.selected(null) and self.enableEdit(false).

So you can simply call these again whenever the page is changed or when a search is done.

self.deselect = function(){
    self.selected(null);
    self.enableEdit(false);
};

this.next = function() {
    self.deselect();
    if(self.pageNumber() < self.totalPages()) {
        self.pageNumber(self.pageNumber() + 1);
    }
}

this.lastpage = function() {
    self.deselect();
    if(self.pageNumber() < self.totalPages()) {
        self.pageNumber(self.totalPages());
    }
}


this.firstpage = function() {
    self.deselect();
    if(self.pageNumber() != 0) {
        self.pageNumber(self.pageNumber()-self.pageNumber());
        alert(self.pageNumber());
    }
}

this.previous = function() {
    self.deselect();
    if(self.pageNumber() != 0) {
        self.pageNumber(self.pageNumber() - 1);
    }
}

Edit: After your comment about the ID, Name and Status not getting updated, I added 3 new observables selectedName, selectedID and selectedStatus. I am using these observables in HTML so that they can be updated whenever selected is changed. This is done by using a subscribe function on selected.

HTML

<input type="text" name="ID" data-bind="value: selectedID, enable: enableEdit" />
<br>Name :
<input type="text" name="Name" data-bind="value: selectedName, enable: enableEdit" />
<br>Status :
<input type="text" name="Status" data-bind="value: selectedStatus, enable: enableEdit" />

JS

self.selected = ko.observable(self.items()[0]);
self.selectedID=ko.observable(self.items()[0].ID());
self.selectedName=ko.observable(self.items()[0].Name());
self.selectedStatus=ko.observable(self.items()[0].Status());

self.selected.subscribe(function(newValue){
  if (newValue === null){
    self.selectedID(null);
    self.selectedName(null);
    self.selectedStatus(null);
    return;
  }
  if (typeof newValue !== 'undefined'){
    self.selectedID(newValue.ID());
    self.selectedName(newValue.Name());
    self.selectedStatus(newValue.Status());
  }
});

Upvotes: 1

Related Questions