8

My jquery code is divided file is divided over 2 files.

In one of the file, I define a function

function something(input){ //does something } 

calling this function only works when the caller line is in the same file. But I need to call it from both files.

If I switch the function to the second file, again I get the same issue. The code in the same file can read it, but not the code in the other file.

2 Answers 2

10

Place your functions outside of $(document).ready(function() { }); to give them global scope. Anything placed within it cannot be accessed from the outside.

You can then look into using a namespace to encapsulate your functions. This helps to avoid clutter of the global namespace.

Sign up to request clarification or add additional context in comments.

Comments

9

You need to create a namespace object, which is shared between your files.

fileA.js

window.mynamespace = window.mynamespace || {}; mynamespace.something = function(input) { // do something }; 

fileB.js

window.mynamespace = window.mynamespace || {}; mynamespace.something(); 

4 Comments

I'm using JQuery and each of my files start like this. Where do I put the namespace? Outside or inside the document ready? $(document).ready(function() { });
@sami: setting or receiving that object should be the very first thing that happens in each of your files. Also, this is a simplified version. You can create a lot more complex solutions for this problem.
I agree this is the best solution. There were also some experimentaion with export/import in JavaScript (see this page) but saving themethods/object on a global object (like window) is the BEST way...
I agree that this is a good solution, but it is not strictly necessary to create this object (so I disagree with "you need to"). A function outside of $(document).ready(function() { }); and other namespaces will be globally available on the page.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.