Search code examples
aureliaaurelia-templating

How can DOM events be used with as-element?


In order to work around issues with browsers not liking anything but table elements in the body of a table, I'm using a custom element for tr like this:

  <tr as-element="session-row" repeat.for="session of sessions" session.bind="session"></tr>

However, this results in any DOM events handlers such as mouseenter.trigger that I put on tr not finding the handler that is in the custom element's view model.

So, I tried injecting the element and adding listeners in the custom element itself:

attached() {
    this.element.addEventListener('pointerenter', this.doPointerEnter);
    this.element.addEventListener('pointerleave', this.doPointerLeave);
}

In this case, the events fire just fine, and they hit the handlers. The problem with this is that it appears that at some point after attached runs, the view model loses the element. Even though, I take the injected element and put it in a local variable, when I want to use it later in one of the event handlers, it's undefined.

I have noticed that if I debug the event handler, this is actually the tr element, but my injected element variable is undefined. In the constructor when I catch the injected element this is the view model.

What am I doing wrong? Is there a better way of achieving this?


Solution

  • You're likely getting bit by the vagaries of this in Javascript.

    Try changing your code to:

    attached() {
        this.element.addEventListener('pointerenter', evt => this.doPointerEnter(evt));
        this.element.addEventListener('pointerleave', evt => this.doPointerLeave(evt));
    }
    

    That should fix the problem for you.