Knockoutjs - Table Row Click Binding, Want to Exclude Columns from Click Event
http://stackoverflow.com/questions/8886046/knockoutjs-table-row-click-binding-want-to-exclude-columns-from-click-event
by johnpapa
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<div style="color:Red; margin:0 0 10px 0;">I want [No Click!] to not fire the select event. And I also don't want to have to put the click binding in each of the td's that I want it to work with.</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: model.Things">
<tr style="cursor:pointer;" data-bind="click: $root.selectThing ">
<td data-bind="text: ID"></td>
<td data-bind="text: Name"></td>
<td>[Click Should Work]</td>
<td data-bind="clickAndStop: $root.blah">[No Click!]</td>
</tr>
</tbody>
</table>
<div style="margin: 15px 0 0 0;">
Selected Row ID: <span data-bind="text: $root.model.CurrentDisplayThing().ID"></span>
</div>
CSS
td
{
padding:5px;
}
JavaScript
ko.bindingHandlers.clickAndStop = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, context) {
var handler = ko.utils.unwrapObservable(valueAccessor()),
newValueAccessor = function() {
return function(data, event) {
handler.call(viewModel, data, event);
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
};
};
ko.bindingHandlers.click.init(element, newValueAccessor, allBindingsAccessor, viewModel, context);
}
};
$(function()
{
function viewModel() {
var self = this;
self.model = {};
self.model.Things = ko.observableArray([
{ ID: 1, Name: "Thing 1" },
{ ID: 2, Name: "Thing 2" },
{ ID: 3, Name: "Thing 3" }
]);
self.model.CurrentDisplayThing = ko.observable(self.model.Things()[0]);
self.selectThing = function(item) {
self.model.CurrentDisplayThing(item);
};
self.blah = function(item) {
alert(item.ID);
}
}
ko.applyBindings(new viewModel());
});