Greg Gum
Greg Gum

Reputation: 37905

How to determine the selected row

I have a table bound like this:

<tbody data-bind="foreach: reportItems">
  <tr>
      <td><a data-bind="text: OrderPostCloseStatusName" data-toggle="modal" data-target="#editStatus"></a></td>

     </tr>
  </tbody>

This works and shows a Bootstrap Model when the link is clicked. However, I need to know which item has been clicked on so that I can show the appropriate data in the model. For example, I would like a property on the ViewModel called selectedItemId that would be bound somehow so the viewModel would know which item is selected when the user clicks the link.

How can I do that?

Greg

Upvotes: 0

Views: 39

Answers (1)

sroes
sroes

Reputation: 15053

Create a new observable in your viewmodel:

self.selectedItem = ko.observable();

Add a click binding to the link:

  <td><a data-bind="text: OrderPostCloseStatusName, click: $root.selectedItem" data-toggle="modal" data-target="#editStatus"></a></td>

Now if you'd like an observable with the selected id, you could create an computed:

self.selectedItemId = ko.computed(function() {
    var selectedItem = ko.unwrap(self.selectedItem);
    if (selectedItem) {
        return ko.unwrap(selectedItem.id);
    }
});

Upvotes: 1

Related Questions