JDR
JDR

Reputation: 1144

KnockoutJS: Checkbox Inside Click-Bound Anchor-Tag not Selectable

I am trying to bind checked on a checkbox input which resides inside an anchor tag which, itself, is click bound.

Whilst I am aware that this may not be entirely valid (interactive content may not be descendant of anchor-tags), I would still like to get it to work as intended - even if just to understand it.

Currently, only the outside click event is handled and the click never arrives at my checkbox.

An example of what I am trying to achieve is here: http://jsfiddle.net/fzmppu93/2/

Having had a look through the KnockoutJS documentation, I tried clickBubble: true on the anchor-tag's click binding - to no avail.

The use case, if you're interested, is an unordered list containing links - each of these "links" contains information on a TV show: title, actors, image, synopsis. The show is selectable, but there are also 'quick-actions' to mark it as seen, star it, and so forth.

Is there another way of making a checkbox work inside an anchor-tag?

Upvotes: 1

Views: 395

Answers (1)

Anish Patel
Anish Patel

Reputation: 4392

I have written a custom binding handler that is similar to "clickBubble", however mines allows to you to prevent the propagation of any event.

Here is the binding handler:

ko.bindingHandlers.preventBubble = {
        init: function (element, valueAccessor) {
            var eventName = ko.utils.unwrapObservable(valueAccessor());
            var arr = eventName;
            if (!eventName.pop) {
                arr = [arr];
            }
            for (var p in arr) {
                ko.utils.registerEventHandler(element, arr[p], function (event) {
                    event.cancelBubble = true;
                    if (event.stopPropagation) {
                        event.stopPropagation();
                    }
                });
            }
        }
    };

And here is a working fiddle of your example.

Upvotes: 2

Related Questions