11

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?

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
    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 Nov 10 '16 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 Mar 19 '18 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.