Reputation: 117
I'm using polymer LitElement and i tried to pass a function to props but did'nt work, this is the way i found to work, but its awfull... Any better suggestions?
import { LitElement, html, customElement, property } from 'lit-element';
@customElement('my-element')
export class MyElement extends LitElement {
onButtonClick = function name (){
console.log("Clicked!!")
}
render() {
return html`
<c-button text="Button Name" onClick="${this.onButtonClick}" />
`;
}
}
@customElement("c-button")
export class CButton extends LitElement{
@property() text;
@property() onClick;
handleClick(){
let fct = eval(`( ${this.onClick} )` )
fct();
}
render(){
return html`
<button @click="${this.handleClick}" > ${this.text} </button>
`
}
}
Upvotes: 6
Views: 5932
Reputation: 11171
@abraham's answer is good for the general case: you can set properties, including functions, with the .
syntax.
However, if you're specifically dealing with events, then I would use event bindings (@
syntax) and make sure the the event you're interested in is either bubbling and composed (as click
is) so that it'll propagate out of the child component, or re-dispatched by the child component. Events are a good model, I'd use them for event-like things.
Upvotes: 5
Reputation: 47833
By default lit-html data bindings set an attribute which means it'll have to convert the value to a string.
Instead of onClick="${this.onButtonClick}"
prefix it with .
like this .onClick="${this.onButtonClick}"
. That will set a property in JavaScript instead and the method will be passed by reference.
Upvotes: 18