JavaScript Controllers and Helpers play a key role in Lightning Components Framework. One of the first things people new to the framework wonder is: What exactly is the difference between JavaScript Controllers and JavaScript Helpers. So let’s go over the differences between them.

 To understand it better, let’s say we have an Account list that shows two Account components (Account.cmp). It may look like this:

Visually, the Account list looks like the 1st picture below. But while running, it actually looks something like the 2nd picture:

Each Account Component component (bundle) is made up of a markup, JavaScript controller, a Helper, a Renderer and more. 

But, while running, the framework creates an instance of the Controller, an instance of the Renderer for each component but creates only one copy of the Helper and passes the reference of the Helper into every Controller instance and every Renderer instance.

In our example with two Account components, the framework creates one copy of the Helper and passes the reference of this Helper into two controller and to two renderer instances.

Benefits:

  • Since Helper is shared across everything, it allows us to share and keep logic across of Controllers and Renderers in one place.
  • It also helps us keep logic within Controllers and Renderers lean.

So we should try to delegate business logic to Helpers whenever possible.

For example:

Instead of:

Do The Following:

 Note: If there are multiple types of components (say, AccountItem.cmp and AccountDetails.cmp), each component type will get a helper of their own.

When To Use Controllers v/s Helpers:

  1. Use Controllers to listen to user events and other events like component, application events. But delegate business logic to helper.

  2. Do similar delegation in all Renderer functions (render, rerender and so on).

  3.  Anytime you need to call one controller function from another controller function, move that logic to Helper.

Anti-Pattern(s):

  1. Too many functions in the Helper: If you get into this situation,  it’s time to refactor the component itself into smaller sub components.

If you have any further questions, please feel free to add comment below or ping me at: @rajaraodv

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS