Controller, Helper and Renderer in Salesforce Lightning and writing multiple javascript functions

Controller,  Helper and Renderer - Relationship

The new Salesforce Lightning provides latest and rich UI experience to the Salesforce application using Components, JavaScript, HTML and CSS (Responsive design) on Lightning Component framework  (a framework built on aura framework). Custom components would be developed and could be used in multiple areas as needed. 

JavaScript plays an important role in Lightning Component framework and inside component bundle, it is separated in to Controller, Helper and Renderer. 

Have you ever wonder, why these are separated?

To know about this, one must know about each section and its role inside the component.

Controller: This section should contain only the JavaScript functions for listening to the different events (User events as well as Control events) that is being fired inside the component. The execution part or the business logic part should be defined under the Helper section.

Helper: This section should should contain only the JavaScript function for handling the business logic of the application. All the server-side calls should be made inside the helper section. The helper functions could be used in both Controller and Renderer.

Renderer: This section should should contain only the JavaScript function for handling the UI changes. The functions inside the Helper section could be called for handling the business logic.

The complete working can be summarized as below:



Key benefits:
  • Easy to identify the code area
  • Easy to maintain
  • Sharing the helper functions
  • More control over the code

How do you write multiple JavaScript functions inside a section

Sometimes you may wonder, how to write multiple functions inside a section and often makes mistakes. If you have noticed, the Javascript function is defined under "({" and "}" brackets as shown below:


Wrongly written:

Sometimes one may make mistake by writing as shown below:

(Mistake-1)

(Mistake-2)

(Mistake-3)



For the first two mistake, while saving it will not provide any error messages, but at run time, you may wonder why only the first function is working. For the third mistake, an error message as shown below is shown, while saving the file.



Correctly written:

The correct way to write the JavaScript functions is to put a comma between the functions  as given below.



Enjoy, writing good scripts!

Comments

Popular posts from this blog

How to get Dynamic SQL Select query to an table variable?