Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

event handler does not update when the property bound to template with onevent is updated #5014

Open
gaurav-rk9 opened this issue Dec 6, 2024 · 2 comments

Comments

@gaurav-rk9
Copy link

Description

when a property is used in template as event handler and later assigned a new value , old value is still used to handle the event (with this being undefined).

Steps to Reproduce

https://stackblitz.com/edit/salesforce-lwc-davchu?file=src%2Fmodules%2Fx%2Fcounter%2Fcounter.js

<template>
    <button onclick={mainHandler}>mainHandler</button>
    &nbsp;
    <button onclick={handlerChanger}>handlerChanger</button>
</template>
import { LightningElement } from 'lwc';

export default class extends LightningElement {
    mainHandler = () => {window.alert('initial');};
    handlerChanger = () => {
        this.mainHandler = () => {window.alert('changed');};
        window.alert(this.mainHandler);
    }
}

Expected Results

New value of mainHandler must be called

Actual Results

Old value of mainHandler is called

Browsers Affected

tested in Chrome : Version 131.0.6778.87 (Official Build) (arm64),
probably in all

Version

  • LWC: 8.11.0

Possible Solution

Additional context/Screenshots
Add any other context about the problem here. If applicable, add screenshots to help explain.

@gaurav-rk9 gaurav-rk9 changed the title property used in template as event handler is not reactive. event handler does not update when the property bound to template with onevent is updated Dec 6, 2024
@nolanlawson
Copy link
Collaborator

nolanlawson commented Dec 6, 2024

This is a limitation of the current LWC template compiler. One workaround is that you can use an object with a property rather than a plain function:

<template>
    <button onclick={handler.onClick}></button>
</template>
export default class extends LightningElement {
  handler = {
    onClick: () => { console.log('foo') }
  }
  connectedCallback() {
    this.handler.onClick = () => { console.log('bar') } // this will be used
  }
}

Demo

@nolanlawson
Copy link
Collaborator

BTW the current behavior has some performance benefits, namely that we can bind/cache the event listener once rather than re-evaluating it. So fixing this may incur a performance cost.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants