I have identified a few operations that you generally do in almost every Lightning Component. Like:
- Almost every Lightning Component makes an action call to server-side methods.
- Almost every Lightning Component shows toast messages based on user actions.
Do you want to write this piece of code again and again in each component or would you like to write this code once and just reuse it in every Lightning Component.
- You need to attach your methods to the window object. These methods will be attached to Secure Window object automatically, which means their scope exist within a namespace. If you do not attach your methods to the window object, you may face error due to Locker Service in place.
- You need to include the static resource in your component in order to use these methods.
- callServer – Call server side methods and on response execute the callback method
- showToast – Show toast messages.
BaseJS.js – Static Resource
- To use it within a Lightning Component, you need to include the static resource file.
- You can call static resource methods similar to the normal methods from the controller or helper file.
Below is the code of SubComponent.cmp lightning component which is using above static resource.
SubComponent.cmp – Component File
SubComponentController.js – Controller File
SubComponentHelper.js – Helper File
- This way you will make your code more centralized, which means in future if any changes need to be done, you have to make those changes in one place and all component will have changed the code.
- This would make debugging easier in case of multiple components are using the same code on the same page.
- The code can be upgraded without touching you lightning components. This means less component to deploy at the time of release.