1
votes

I am trying to populate an HTML5 table using Knockout.js. Populating the table works great, until I try to make each table row a "link" to the entity the row is about. In particular, my HTML5 looks like:

<tr class="collection-row" data-bind="attr: { 'data-url': itemUrl }">
  <td data-bind="text: view.date">
  <td data-bind="text: view.title">
  <td data-bind="text: view.author">

The idea being that the tr should end up with a data-url attribute which points at itemUrl (a computed observable). I hoped that I would be able to do something along the lines of:

$(".collection-row").click(function(){
  window.location.href = $("this").data("url");
});

to turn the whole row into a "link" to itemUrl. This works great, except that it doesn't at all. When I click, I get sent to /admin/undefined. I can confirm that the itemUrl observable is returning the correct URL. So it looks like jQuery can't see Knockout's data-url attribute binding. How should I proceed?

1
Try using jQuery on to set the click binding. Maybe the click binding is being registered on the DOM element before Knockout has finished all the bindings - rwisch45
I gave that a try, and it didn't work. I ended up going with a variation of the accepted answer. - nomen

1 Answers

2
votes

I would think about using knockout for this sort of thing.

with knockout you can bind to the click event and it passes the item that was clicked to the function.

on your viewModel you would have something like

var vm = function(){
    var self = this;
    self.arrayData = ko.observableArray([]);
    self.gotoPage = function(item){
        window.location.href = item.itemUrl();
    };

}

Your HTML then becomes

<tr class="collection-row" data-bind="click: $root.gotoPage">
  <td data-bind="text: view.date">
  <td data-bind="text: view.title">
  <td data-bind="text: view.author">
</tr>