KnockoutSpa (router.ts) Event listener and non trivial a tags #1423

Closed
opened 2025-08-09 17:20:05 +00:00 by fergalmoran · 0 comments
Owner

Originally created by @cmdkeen on 8/21/2016

The code for the clickEventListener in router.ts does not capture the click event on a tags that contain child elements:

<a data-bind="attr: { href: url }"
    <span data-bind="text: text"></span>
</a>

Whereas the non tag version works fine.

<a data-bind="attr: { href: url }"
    <!-- ko text: url --><!-- /ko -->
</a>

Switching to use the jQuery event selector and using currentTarget fixes everything for me. There's probably a Vanilla JS way of achieving the same thing but jQuery is in the project already and it is a schoolnight.

this.clickEventListener = evt => {
    let target: any = evt.currentTarget;
    if (target && target.tagName === 'A') {
        let href = target.getAttribute('href');
        if (href && href.charAt(0) == '/') {
            history.push(href);
            evt.preventDefault();
        }
    }
};

$(document).on('click', 'a', this.clickEventListener);
*Originally created by @cmdkeen on 8/21/2016* The code for the clickEventListener in router.ts does not capture the click event on a tags that contain child elements: ``` <a data-bind="attr: { href: url }" <span data-bind="text: text"></span> </a> ``` Whereas the non tag version works fine. ``` <a data-bind="attr: { href: url }" <!-- ko text: url --><!-- /ko --> </a> ``` Switching to use the jQuery event selector and using currentTarget fixes everything for me. There's probably a Vanilla JS way of achieving the same thing but jQuery is in the project already and it is a schoolnight. ``` this.clickEventListener = evt => { let target: any = evt.currentTarget; if (target && target.tagName === 'A') { let href = target.getAttribute('href'); if (href && href.charAt(0) == '/') { history.push(href); evt.preventDefault(); } } }; $(document).on('click', 'a', this.clickEventListener); ```
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github/JavaScriptServices#1423
No description provided.