html inject call function with parameter

229 views Asked by At

I have a problem where if i want to add a parameter to my click attribute then it calls the function as soon as it renders

here is my test html:

return html`
       <button class="menu-btn" @click="${this._OpenSubMenu(1)}>test</button>" 
`;

}

And the function:

_OpenSubMenu(test:number) {
    console.log("Hello")
  }

This output Hello as soon as the page is rendered.

So how can i avoid this while still adding a parameter to my function?

1

There are 1 answers

2
Keith On BEST ANSWER

You need to make your function return a function. Your click function will then execute the returned function, and due to closure's will still have access to the params.

eg..

_OpenSubMenu(test:number) {
  var that = this;
  return function () {
     console.log("Hello");
     //test is also a closure so you can use here
     //that will equal this
  }
}

If you want access to this, you could also use an arrow function

_OpenSubMenu(test:number) {
  return () => {
     console.log("Hello");
     //test is also a closure so you can use here
     //this will also still be valid here
  }
}