Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function defined in one js file is undefined in another js file

According to this answer my function call should be working but it isnt: Calling a javascript function in another js file

My code (simplified):
file1.js:

$(document).ready(function(){
  function loadFYfResults(sizes){
      alert('hello');
  }
});

file2.js

$(document).ready(function(){
  $('.size-button').click(loadFYfResults(sizes));
});

theme.liquid
in the head:
{{ 'file1.js' | asset_url | script_tag }}
{{ 'file2.js' | asset_url | script_tag }}


When the function is called, the console throws this error:
"Uncaught ReferenceError: loadFyfResults is not defined"
My site is built using Shopify's liquid theme platform but I'm not sure if that has anything to do with it. Can anyone spot what I am doing wrong?

like image 566
Tatiana Frank Avatar asked Oct 12 '15 00:10

Tatiana Frank


1 Answers

The functions are out of scope of one another. You can see this by looking at this block:

$(document).ready(function(){
    function loadFYfResults(sizes){
        alert('hello');
    }
});

console.log(loadFYfResults);

In this case, loadFYFResults will be undefined as it is no longer in the scope where loadFYfResults was defined.

For you to use that function in another file, there will have to be another reference in the outer scope to your loadFYfResults function, or just take it out of the $(document).ready wrapper since you know that it will only be called when the document is ready by the second function.

like image 122
David Li Avatar answered Nov 15 '22 01:11

David Li