4

I have a main page, with a main controller, that contains some JavaScript code:

<apex:page controller = "controller1">
  <script>
    function function1(){
     //I want to call the function 2 here
    }
  </script>
</apex:page1>

And a component with some JavaScript code too:

<apex:component controller="controller2">
 <script>
   function2(){ //Some code here }
 </script>
</apex:component>

Well, I want to call the function 2, contained in the component, into my main page, like in the code above...

Is it possible? If yes, how?

The function2 in my component's JavaScript code refers to a method in my controller2, but I don't know if this information is useful for this problem.

1

We can access directly.

<apex:page controller="OppsController">
    <apex:form >
        <c:Test></c:Test>
        <input type="button" value="test" onclick="test();"/>
        <script>
        function test(){ 
        function2();
        }
        </script>
    </apex:form>
</apex:page>

Component

<apex:component >
    <script>
   function function2(){
   alert('in component');
   }
 </script>
</apex:component>
  • Thank you for the detailed answer @Ratan ! It seems to be working with my code :) – dou Dec 21 '15 at 9:34
1

I'm not entirely sure if this would work and assuming you want function1() to be called as soon as the page loads to call function2(), here are some ideas:

First things first would be to check whether or not the JavaScript code is rendered into the page. Make sure that when you view the page source, function2() exists in there.

The next thing I would do is to only call function1() when the DOM has loaded. If you're using jQuery, that might look a little like this:

$(document).ready(function() {
  function1();
})

function1() {
  function2();
}

If you're using pure JavaScript, that'd be something like below:

window.onload = function() {
  function1();
}

function1() {
  function2();
}

If it is that you're calling function1() only to call function2(), and it has no other logic or requirement, you wouldn't really need function1() at all, and you could just call function2() within the onload or $(document).ready() functions themselves.

  • I need the function1 to call 3 functions from 3 components, and then I call the function1 into a button, like in the Ratan's answer (my fault, I forgot to say that into my question...) but I keep your answer in mind for other javascrip problems, thank you :) – dou Dec 21 '15 at 9:39
  • @dou No problem, glad it's somewhat useful! :) – Dan Jones Dec 21 '15 at 9:40

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.