3

I created a lightning component that will house a drag and drop file uploader and handle all of its goings ons.

Then I bring it into my Visualforce page like so:

$Lightning.use('c:DropZoneComponentApp', function(){    
    $Lightning.createComponent('c:DropZoneComponent', {eventId: currentEvent.taskId}, 'eventDropzone', function(cmp){
        console.log('Component Created!', cmp);
        console.log(cmp.get('v.fileInfo'));
        //console.log(cmp.testingFunction()); <--Doesn't work
    });
});

I now want to be able to call functions of the lightning component when a button is pressed on my Visualforce page. just doing cmp.functionName() does not seem to work.

How do you accomplish this? I am OK triggering the AuraEnabled controller methods for the component, or the javascript controller methods.

5

You can use aura:method to invoke lightning controller methods as follows. Store the generated component to a global variable and invoke the aura:method to call your controller action. You can either call lightning controller methods which could, in turn, call the @AuraEnabled Methods or use RemoteActions to call your apex class methods, it really depends on your use case.

Component:

<aura:component access="global">

    <aura:method name="sampleMethod" action="{!c.doAction}" description="Sample method with parameters" access="global"> 
        <aura:attribute name="foo" type="String" default="parameter 1"/> 
        <aura:attribute name="bar" type="Object" /> 
    </aura:method>

    Inside Component

</aura:component>

Controller:

({
    doAction : function(component, event, helper) {
        var params = event.getParam('arguments');
        if (params) {
            console.log(params.foo);
            console.log(JSON.stringify(params.bar));
        }
    }
})

Visualforce Page:

<apex:page >
    <apex:includeLightning />
    <div id="lightning" />
    <script type="text/javascript">
        var cmp; 

        $Lightning.use("c:TestApplication2", function() {
            $Lightning.createComponent("c:Component1",{},"lightning",
            function(component) {
              cmp = component; 
            });
        });

        var invoke_aura_method = function(){
            cmp.sampleMethod("Hello World ! ", {message : "I'm Jack Sparrow"});
        }

    </script>

    <apex:form >
        <apex:commandButton value="Call Aura Method" onclick="invoke_aura_method();return false;"/>
    </apex:form>

</apex:page>

Example:

Sample Aura Method

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.