Reputation: 4144
I have a table populated by KnockoutJS. HTML code looks like
<table>
<thead>
<tr>
<th class="col_name">Name</th>
<th class="col_dob">DOB</th>
<th class="col_address">Address</th>
</tr>
</thead>
<tbody data-bind="foreach: rows">
<tr data-bind="attr: { id: resource.id},
css: {'isSelected':$root.selRow() == $data},
click: $parent.highlightRow.bind($parent),
event : { dblclick: $parent.processRow.bind($parent) }">
<td class="col_name" data-bind="text: resource.name"></td>
<td class="col_dob" data-bind="text: resource.birthDate"></td>
<td class="col_address" data-bind="text: resource.address"></td>
</tr>
</tbody>
</table>
I can highlight with a single-click and execute and event on a double-click however when I try to get a data from selected row I'm getting only selected DOM information without data.
KnockoutJS code for that part looks like:
this.selectedRow = ko.observable(null);
this.processRow = function(item)
{
var self = this;
self.selectedRow(item);
console.log("Selected data to process: " + JSON.stringify(self.selectedRow(item)));
}
How can I get data from selected row then? Should I do not use bind
to $parent
in that case? If so how do I know which row was selected?
Upvotes: 0
Views: 1484
Reputation: 4304
Your item data is being passed into the function correctly, but you're outputting to the console the result of a set operation, which is blank. You've already set the value of selectedRow so there isn't a need to set it again. The console.log line should be reading the value instead of setting it.
this.processRow = function(item)
{
var self = this;
self.selectedRow(item);
console.log("Selected data to process: " + JSON.stringify(self.selectedRow()));
}
function viewModel (){
this.selectedRow = ko.observable(null);
this.rows = ko.observableArray([
{resource: new resource()}, {resource: new resource()}, {resource: new resource()}]);
this.processRow = function(item)
{
var self = this;
self.selectedRow(item);
console.log("Selected data to process: " + JSON.stringify(self.selectedRow()));
}
}
function resource(){
this.name = 'resource name';
this.birthDate = '1/1/1900';
this.address = '123 address ln.'
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr>
<th class="col_name">Name</th>
<th class="col_dob">DOB</th>
<th class="col_address">Address</th>
</tr>
</thead>
<tbody data-bind="foreach: rows">
<tr data-bind="event : { dblclick: $parent.processRow.bind($parent) }">
<td class="col_name" data-bind="text: resource.name"></td>
<td class="col_dob" data-bind="text: resource.birthDate"></td>
<td class="col_address" data-bind="text: resource.address"></td>
</tr>
</tbody>
</table>
Upvotes: 1