Is there a way to handle a Lightning Event from a Visualforce Page using Lightning Out?

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?

Answer

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});

    });
}); 

Attribution
Source : Link , Question Author : Grokodile , Answer Author : Grokodile

Leave a Comment