12

It's documented that Lightning Events can be fired from Non-Lightning code.

However, I'm looking for a way to do the opposite.

I'd like to be able to create a lightning component that will function in Lightning Experience and both Sales Cloud and Service Cloud (the console) via Lightning Out.

When I'm using Lightning Out I'd like to be able to handle events and adapt them for the context as needed.

I can define a javascript function on the Visualforce page, handle the events within the component and then call the function I've defined e.g.:

// My.vfp within <script></script>
var visualForceFunction = function(data){
    console.log(data);
};

// c:My.cmp
<aura:handler name="change" value="{!v.myAttribute}" action="{!c.onMyAttributeChanged}" />

// c:MyController.js
onMyAttributeChanged : function (c, e, h) {
    if(typeof visualForceFunction === 'function'){
        visualForceFunction('foo');
    }
}

However this breaks encapsulation since my component needs to know about a function on the Visualforce page which is hosting it.

I'd rather raise a Lightning Event and be able to hook up an event handler near to $Lightning.use(...) but I'm not sure if this is possible?

1 Answer 1

13

Eureka!

Raising the Application event from the component:

// c:MyController.js
onMyAttributeChanged : function (c, e, h) {
    var myEvent = $A.get("e.c.MyApplicationEvent");
    myEvent.setParam("myEventData1", "some event data");
    myEvent.fire();
}

Handling the Application event on the Visualforce page:

// My.vfp within <script></script>
var visualForceFunction = function(event){
    var myEventData1 = event.getParam("myEventData1");
    console.log(myEventData1);
};


// and...
$Lightning.use("c:MyLtngOutApp", function() {
    $Lightning.createComponent("c:MyComponent", {}, "lightning", function(){

        $A.eventService.addHandler({ "event": "c:MyApplicationEvent", "handler" : visualForceFunction});

    });
}); 
3
  • 3
    This solution requires the Lightning component be inserted into the VisualForce page. Is there a solution where the Lightning component is a sibling of the VisualForce page with both on a Lightning Page?
    – Lounge9
    Commented Nov 10, 2016 at 4:26
  • I am getting the impression that it isn't possible to raise a COMPONENT event (rather than APPLICATION event) from the component and have that handled in the Visualforce page - it isn't working for me and I can't find any examples of such usage.
    – Phil W
    Commented Mar 19, 2018 at 15:44
  • In my case I used the force:navigateToComponent event, but I also had to declare it in the component with <aura:registerEvent name="force:navigateToComponent" type="force:navigateToComponent" />. To make it even more confusing, in the controller I must refer to it as e.force:navigateToComponent. Commented May 6, 2020 at 14:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .