Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockoutjs - Table Row Click Binding, Want to Exclude Columns from Click Event

Tags:

knockout.js

I am trying to use knockout to bind a click to a row in a table like this:

<tr data-bind="click: $root.selectItem">

It works great. The problem is when I try to exclude certain columns from taking the click action. I am have edit and delete buttons in my row and I don't want them firing the selectItem click event. Am I going to just have to bind all the td's I want to behave this way to the click event or is there an easier way to do it?

Fiddle here: http://jsfiddle.net/blankasaurus/WYKEM/

like image 599
Jason Avatar asked Jan 16 '12 20:01

Jason


1 Answers

Update: you avoid a custom binding by adding clickBubble: false as an additional binding with the click binding as suggested by Kevin Obee and demonstrated in this sample: http://jsfiddle.net/kevinobee/Q25ja/2/

Original: You can use a custom binding that wraps the click binding and prevents additional events from happening. It might look like:

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);    
    }
};

Here is a sample: http://jsfiddle.net/rniemeyer/xj7Hs/

like image 52
RP Niemeyer Avatar answered Oct 22 '22 05:10

RP Niemeyer