Usability - Productivity - Business - The web - Singapore & Twins

Creating a Lightning Service

When you develop in Lightning your client side architecture can benefit as much as the server from a separation of concerns. The component library is testimony to that.

Out of the box services

The Component Library features a growing number of services:

Building your own

There is more than one way to skin you cat. You can do:

  • Lightning Style
    Philippe Ozil described in detail how to use and create your own services 'lightning style'. You should check out his Server Side Actions Service that allows you cut down on boiler plate code substantially
  • JavaScript Style
    Establish a global service extending the Window object
  • ES6 Style
    Import a JavaScript module. This would need to setup Babel - not too practical for now

Extending the window object

When you extend the window object, which is the browser's top level object, the service becomes available "standalone", like alert() (which is actually window.alert()). A service could look like this:

window.demoLib = ( function() {
 let someMethod = () => {
  return 'Something'

 let helloMethod = (paul) => {
  return `Hello ${paul}`;

 return {someMethod, helloMethod};

This will now provide you with demoLib.someMethod() returning Something and demoLib.helloMethod('World') returning "Hello World". The final step to enable such a library is to add ltng:require to your components: <ltng:require scripts="{!Resource.demoLib} afterScriptLoaded="someMethodIfRequired" /> presuming you stored your JS in resources as demoLib.js. The Aura framework will make sure that the library is loaded once only, regardless how many components define it as dependency.

What can go wrong?

There are a few caveats:

  • For hard core Apex developers: JavaScript is case sensitive
  • You need to be clearly communicating service names to other developers in your org. If someone has the idea to name a library the same as yours, things will break. Good practice is to check if your library and function is available: if (window.demoLib && window.demoLib.someMethod) {...}
  • Fat arrow functions () => {...} are not supported in legacy browsers, so you need the slightly more verbose function(){...} (beware the this keyword behaves different then).

As usual YMMV

Posted by on 19 October 2018 | Comments (0) | categories: JavaScript Lightning Salesforce


  1. No comments yet, be the first to comment