Toggle Side Panel

  • Home
  • Articles
    • All Articles
    • Blogs
    • Videos
    • Infographics
  • Consultants
    • Salesforce Product Expertise
      • Top Salesforce ConsultantsTop Salesforce Consultants
      • Marketing Cloud ConsultantsMarketing Cloud Consultants
      • Service Cloud ConsultantsService Cloud Consultants
      • Experience Cloud ConsultantsExperience Cloud Consultants
      • Analytics Cloud ConsultantsAnalytics Cloud Consultants
    • Salesforce Industry Expertise
      • Non-Profit Cloud ConsultantsNon-Profit Cloud Consultants
      • Financial Service Cloud ConsultantsFinancial Service Cloud Consultants
      • Health Cloud ConsultantsHealth Cloud Consultants
      • Commerce Cloud ConsultantsCommerce Cloud Consultants
      • Manufacturing Cloud ConsultantsManufacturing Cloud Consultants
    • Salesforce Experts by Location
      • USATop Salesforce Consultants in USA
      • IndiaTop Salesforce Consultants in India
      • AustraliaTop Salesforce Consultants in Australia
      • United KingdomTop Salesforce Consultants in UK
      • CanadaTop Salesforce Consultants in Canada
  • Webinars
  • Marketplace
  • Advertise With Us
  • Contact Us
  • Discussions
More options
    Sign in Sign up
    • Home
    • Articles
      • All Articles
      • Blogs
      • Videos
      • Infographics
    • Consultants
      • Salesforce Product Expertise
        • Top Salesforce ConsultantsTop Salesforce Consultants
        • Marketing Cloud ConsultantsMarketing Cloud Consultants
        • Service Cloud ConsultantsService Cloud Consultants
        • Experience Cloud ConsultantsExperience Cloud Consultants
        • Analytics Cloud ConsultantsAnalytics Cloud Consultants
      • Salesforce Industry Expertise
        • Non-Profit Cloud ConsultantsNon-Profit Cloud Consultants
        • Financial Service Cloud ConsultantsFinancial Service Cloud Consultants
        • Health Cloud ConsultantsHealth Cloud Consultants
        • Commerce Cloud ConsultantsCommerce Cloud Consultants
        • Manufacturing Cloud ConsultantsManufacturing Cloud Consultants
      • Salesforce Experts by Location
        • USATop Salesforce Consultants in USA
        • IndiaTop Salesforce Consultants in India
        • AustraliaTop Salesforce Consultants in Australia
        • United KingdomTop Salesforce Consultants in UK
        • CanadaTop Salesforce Consultants in Canada
    • Webinars
    • Marketplace
    • Advertise With Us
    • Contact Us
    • Discussions
    Close search

    Activity › Forums › Salesforce® Discussions › Sharing Javascript between salesforce lightning components

    Tagged: Javascript in Salesforce, JS Controller, Manual Sharing, Salesforce Apex, Salesforce Lightning, Salesforce Lightning Components, Sharing Rule

    • Salesforce® Discussions

      Sharing Javascript between salesforce lightning components

      Posted by Kumar on December 22, 2016 at 1:54 PM

      Hi all,
      In a Lightning Component we have the notion of a JavaScript controller and a helper. We can use the helper to call code from the JavaScript controller that is shared between functions, so we can reduce redundancy in the code. This all works great.

      However, I was wondering if it is possible, and if so how, to share code between multiple Lightning Components. It doesn't behave like Apex where you can just reference other class.

      Is there any hack for this?

      Thanks

      Jade replied 7 years ago 4 Members · 3 Replies
      • Javascript in Salesforce
      • JS Controller
      • Manual Sharing
      • Salesforce Apex
      • Salesforce Lightning
      • Salesforce Lightning Components
      • Sharing Rule
    • 3 Replies
    • Vikas Kumar

      Member
      January 20, 2017 at 2:22 PM

      Hi Kumar,

      Currently the recommended mechanism for this is to use a Static Resource and include it in any components that need to share the same JavaScript via ltng:require (loads the library once and only once similar to requirejs).

    • CloudGenie

      Member
      February 7, 2017 at 9:26 AM

      Hi Vikas, can we use another parameter in " ltng:require "

    • Jade

      Member
      November 23, 2018 at 9:32 AM

      Hi Kumar,

      Lightning Component Framework is built on OOPS concept, not exactly but somehow. So to answer to your question, you can reuse the functions of one component's HELPER in another Component.

      Lightning Component inheritance is similar to object-oriented inheritance in programming languages like Apex or Java.  When a sub component extends a super component it inherits the super component’s attributes, event handlers, and helper methods.  The controller methods of the super component can be called by the sub component but the documentation warns not to do that and suggests that it may become deprecated.  The recommended approach is to use the helper for any super component code a sub component needs to use.  Additionally, abstract components and interfaces can be created.

      When you want to create a component that can be extended you must set a value of true for the extensible attribute of the aura:component. By default, components are not extensible, just like Apex classes are not. You must put {!v.body} inside your base component’s code. This will allow your base component to handle the events generated by Sub Components.

      Super Component: Base.cmp

      <aura:component extensible="true">

      {!v.body}

      </aura:component>

      Super Component Helper: BaseHelper.js

      ({
      callServer : function(component, method, callback, params, setStorable) {
      var action = component.get(method);

      //Set params if any
      if (params) {
      action.setParams(params);
      }

      if(setStorable){
      actions.setStorable();
      }

      action.setCallback(this,function(response) {
      var state = response.getState();
      if (state === "SUCCESS") {
      // pass returned value to callback function
      callback.call(this,response.getReturnValue());
      } else if (state === "ERROR") {
      // generic error handler
      var errors = response.getError();
      if (errors) {
      console.log("Errors", errors);
      this.showToast({
      "title": "ERROR IN SERVER CALL",
      "type": "error",
      "message": errors
      });
      if (errors[0] && errors[0].message) {
      throw new Error("Error" + errors[0].message);
      }
      } else {
      throw new Error("Unknown Error");
      }
      }
      });

      $A.enqueueAction(action);
      },

      /*
      * This function displays toast based on the parameter values passed to it
      * */
      showToast : function(params) {
      var toastEvent = $A.get("e.force:showToast");
      if(toastEvent){
      if(!params){
      toastEvent.setParams({
      "title": "TOAST ERROR!",
      "type": "error",
      "message": "Toast Param not defined"
      });
      toastEvent.fire();
      } else{
      toastEvent.setParams(params);
      toastEvent.fire();
      }
      } else{
      alert(params.message);
      }
      },
      })

      Sub Component: SubComponent.cmp - Extends Base Component in Component Definition

      <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes"

      extends="c:Base" controller="AccountController" access="global" >

      <aura:attribute name="data" type="Account[]"/>
      <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

      <aura:iteration items="{!v.data}" var="acc">
      <p><lightning:formattedText value="{!acc.Name}" /></p>
      </aura:iteration>
      </aura:component>

      Sub Component Controller - SubComponentController.js

      ({

      doInit : function(component, event, helper) {

      helper.getAllAccounts(component, helper);

      },

      })

      Sub Component Helper - SubComponentHelper.js

      ({

      getAllAccounts : function(component, helper) {

      //Calling base component's helper method to call Aura Method

      helper.callServer(component, "c.getAccounts",

      function(response){

      if(response){

      component.set("v.data", response);

      //Calling showToast method of Base component

      helper.showToast({

      "title": "SUCCESS",

      "type": "success",

      "message": "Account details are loaded"

      });

      }

      });

      },

      })

      This is how you can share the same code between multiple components and avoid boiler plate codes.

      Few Important Points :

      • Attributes of the component markup, Controller and Helper methods gets inherited and can be used by Sub Components. Along with these, events are also get inherited which can be handled by both Base and Sub Components.
      • You must make your base component, either abstract=true or extensible=true.
      • Your Base component markup must include “{!v.body}”

      Hope this will help.

      Thanks

    Log In to reply.

    • Public
    • All Members
    • My Connections
    • Only Me
    • Public
    • All Members
    • My Connections
    • Only Me
    • Public
    • All Members
    • My Connections
    • Only Me

    application solution

    Popular Salesforce Blogs

    AppExchange vs Custom Development: Considering Your Options in Salesforce

    Blog in Salesforce

    Salesforce AppExchange is a marketplace of pre-built applications and components that you can install into your Salesforce organization. Custom development is the process of building…

    AppExchange, Custom Development
    Apphienz Dec 29, 2022
    1,753  Views
    Salesforce Docusign Integration

    Salesforce with DocuSign

    Blog in Salesforce customization, Salesforce integration

    Introduction In this era of information where everything is online so why should we wait for paper-based signing of a document when it can be…

    CLOUD, Cloud Computing, Installing Force.com, JavaScript, Salesforce AppExchange
    Mohit Sep 26, 2016
    27,823  Views
    Setting SSO Between Salesforce and Okta’s Salesforce.com Standard Application using SAML 2.0 protocol

    Setting SSO Between Salesforce and Okta’s Salesforce.com Standard Application using SAML 2.0 protocol

    Blog in Others

    SSO(Single Sign On between Okta(Salesforce.com application) as Identity Provider and Salesforce as Service Provider) Steps to setup SSO between Salesforce and Okta’s Salesforce.com Application:- Go…

    Assignment Tab, Configuration, Dashboards, Identity Provider, Login URL
    shariq Sep 10, 2018
    11,455  Views

    Popular Salesforce Videos

    Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    Video in Salesforce Training

    Hello Trailblazers, In this video, we will learn how to use Aura Component in Salesforce Screen Flow. How to validate the Lightning Component Input from…

    Salesforce Training, Salesforce Tutorial, salesforce, Salesforce Learning, Lightning Component
    Abhishek Nov 15, 2021
    3,695  Views
    Data Archiving in Salesforce | Backup and Restore

    Data Archiving in Salesforce | Backup and Restore

    Video in Salesforce Apex, Salesforce Training

    Learn the techniques, patterns and strategies when it comes to handling data archiving, backup and restores. Watch this video and learn all about it, do…

    Salesforce Training, Salesforce Tutorial, Salesforce Video, Salesforce Learning, Techniques
    Prafull Sep 28, 2021
    2,081  Views
    Salesforce Nonprofit Cloud Explained

    Salesforce Nonprofit Cloud Explained

    Video in Salesforce For Nonprofits

    Discover how Salesforce Nonprofit Cloud helps organizations drive social change through better donor management, volunteer coordination, and streamlined operations. In this video, we'll explore the…

    Salesforce Nonprofit Cloud, Nonprofit CRM Solutions, Nonprofit Technology, Donor Management CRM, Nonprofit Management Software
    Dean Sep 5, 2025
    79  Views
    Footer Forcetalks logo

    support@forcetalks.com

    • twitterx

    Quick Links

    Advertise with Us

    Salesforce® Articles

    Dreamforce 2023

    Top Salesforce® Bloggers 2023

    Top Salesforce Consultants

    Get Listed

    Company

    Contact Us

    About Us

    Privacy Policy

    Terms & Conditions

    InsightHub

    Salesforce Blogs

    Salesforce Videos

    Salesforce Groups

    Salesforce Jobs

    © 2025 - Forcetalks ● All Rights Reserved

    Salesforce® is a trademark of Salesforce® Inc. No claim is made to the exclusive right to use “Salesforce”. Any services offered within the Forcetalks website/app are not sponsored or endorsed by Salesforce®.

    Try AuditMyCRM - It is a Salesforce CRM Audit tool which comprehensively scans your Salesforce org and gives you the list of errors or warnings you need to take care of.
    We use cookies to enhance your browsing experience. Please see our privacy policy if you'd like more information on our use of cookies.