开发者

Reusable function from an external script

开发者 https://www.devze.com 2023-02-01 21:14 出处:网络
Simplified Example: // path/to/js开发者_如何学Python/panel.js $(function(){ var hidePanel = function(){

Simplified Example:

// path/to/js开发者_如何学Python/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() {
}

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

0

精彩评论

暂无评论...
验证码 换一张
取 消