For common methods that should be used in multiple places, you have three basic choices.
First, you can export the method, and then call it from your component.
let test1 = false
function handleClick(event) {
this.clickedButtonLabel = event.target.label;
test1 = true
}
export { handleClick }
Note that in this case, this
is undefined by default, and test1
will be shared by all components that use this method. In other words, test1 is effectively a static variable. You can fix this
with .bind
:
handleClick.bind(this)(event);
Note that the imported method won't be part of the class, so you can't use it in a template directly; you'd have to assign it to a property first:
export default class HelloWorld extends LightningElement {
handleClick = handleClick;
}
Second, you can create a mixin class for common methods:
const Utils = (superclass) => class extends superclass {
handleClick(event) {
this.clickedButtonLabel = event.target.label;
}
}
export { Utils }
Which you then use in the main component:
import { LightningElement } from 'lwc';
import { Utils } from 'c/utils';
export default class HelloWorld extends Utils(LightningElement) {
// .. rest of code
This has the advantage of placing the method directly into the controller, so it can be called directly from a template:
<div onclick={handleClick}>...</div>
Mixins allow you to combine multiple units at once, so it is more flexible than class inheritance.
The third option is to extend a LightningElement
:
// utils
import { LightningElement } from 'lwc';
class CustomElement extends LightningElement {
handleClick(event) {
...
}
}
export { CustomElement }
Which you can then use as a replacement for LightningElement:
// helloWorld.js
import { CustomElement } from 'c/utils';
export default class HelloWorld extends CustomElement {
...
}
Like the second option, this automatically fixes "this". If you have a lot of components that have very similar structure, this can also be a useful technique.
Note that, in all of these examples, test1
is fixed to the file in which is defined in. In other words, HelloWorld
won't be able to access test1
in any of the three scenarios. It is a part of utils
, and so can't be directly accessed from outside the utils.js
file (unless exported).