简体   繁体   中英

Reusable function from an external script

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...

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 .

// 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() {
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM