0

Simplified Example:

// path/to/js/panel.js
$(function(){
    var hidePanel = function(){
        //hides the panel div
    };
});

// path/to/js/another-script.js
$(function(){
    hidePanel(); //out of scope MEGA-FAIL
});

As we speak, i have some functions/variables copy-pasted in 2 different files. I was curious whether RequireJS would solve this problem...

2 Answers 2

3

Your function itself just needs to be declared after jQuery is loaded if it needs jQuery, but it need not be declared on document.ready, just executed then. The simplest way to do what you're after is:

// path/to/js/panel.js
function hidePanel() {
 //hides the panel div
}

// path/to/js/another-script.js
$(hidePanel);

This just passes your function to $(), which schedules it run on document.ready, or immediately if the document is already ready.

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

4 Comments

This will work in the simplified case scenario, but panel.js has various variables and i intend to use them in "another-script.js". I think i 'll have to make a Panel() object in this case. :)
@fuSi0N - you can do that, or if you just need one copy: var Panel = { hide: function() { ... }, otherFunc: function() { ... } }; would work.
I don't follow, can i use $(Panel); and then use Panel.hide(); in "another-script.js"?
@fuSi0N - For the another-script.js if you want to run the hide function, it would be: $(Panel.hide); :)
0
// path/to/js/panel.js
$(function(){
    var hidePanel = function(){
        //hides the panel div
    };
});

With this code you create an an anonymous function. Anonymous functions don't pollute the global namespace. All variables (in this case hidePanel) declared in an anonymous function are not visible outside of the anonymous function. Because of that the function is not available.

So you need to do a global function. You can make that in different ways:

var hidePanel = function() {
});

function hidePanel() {
}

P.S: I recommend that you learn the OO-Pattern for javascript :-) Javascript Object-Oriented Programming | Part 1

1 Comment

I'm currently reading "Object-Oriented Javascript" book by Stoyan Stefanov and searching for ways to remove some complexity of an existing project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.