Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia `click` attribute that requires event target to be same as element

Tags:

aurelia

I'm aware of click.trigger as well as click.delegate which work fine. But what if I want to assign a click event that should only trigger when the exact element that has the attribute gets clicked?

I'd probably do something like this were it "normal" JS:

el.addEventListener('click', function (e) {
    if (e.target === el) {
        // continue...
    }
    else {
        // el wasn't clicked directly
    }
});

Is there already such an attribute, or do I need to create one myself? And if so, I'd like it to be similar to the others, something like click.target="someMethod()". How can I accomplish this?

Edit: I've tried this which doesn't work because the callback function's this points to the custom attribute class - not the element using the attribute's class;

import { inject } from 'aurelia-framework';

@inject(Element)
export class ClickTargetCustomAttribute {
    constructor (element) {
        this.element = element;

        this.handleClick = e => {
            console.log('Handling click...');

            if (e.target === this.element && typeof this.value === 'function') {
                console.log('Target and el are same and value is function :D');

                this.value(e);
            }
            else {
                console.log('Target and el are NOT same :/');
            }
        };
    }

    attached () {
        this.element.addEventListener('click', this.handleClick);
    }

    detached () {
        this.element.removeEventListener('click', this.handleClick);
    }
}

And I'm using it like this:

<div click-target.bind="toggleOpen">
    ....other stuff...
</div>

(Inside this template's viewModel the toggleOpen() method's this is ClickTargetCustomAttribute when invoked from the custom attribute...)

I'd also prefer if click-target.bind="functionName" could instead be click.target="functionName()" just like the native ones are.

like image 576
powerbuoy Avatar asked Oct 25 '25 19:10

powerbuoy


1 Answers

Just use smth like click.delegate="toggleOpen($event)". $event is triggered event, so you can handle it in toggleOpen

toggleOpen(event) {
    // check event.target here
}

Also you can pass any other value available in template context to toggleOpen.

like image 161
valichek Avatar answered Oct 29 '25 06:10

valichek