views:

184

answers:

4

Hi all,

I have several functions which use jquery that are called across different pages. I'm wondering if it's possible to define these functions in a single file, and then call them in different files which are included after the initial file.

Here's an example:

## default.js
$(function() {
    // jquery specific functions here...
    function showLoader(update_area) {
        update_area.ajaxStart(function() {
            update_area.show();
            $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
        });
    }   
});

## other_file.js (included after default.js)
update_area = $('#someDiv');
showLoader(update_area);

When I do this, firebug gives me 'showLoader is not defined. I'm assuming that's because of the scope of the $(function() { }); which contains the jquery-specific functions. If that's the case, though, doesn't that mean I'll need to have the same code defining the functions in each js file I call them in?

How can I separate these things properly?

Thanks!

A: 

You need to resolve dependencies by yourself if I am not mistaking. Isn't there a script loader facility in jquery?

jldupont
+3  A: 

You don't have to put the definition of showLoader into $(function(){}), but the call of showLoader, e.g.:

## default.js

function showLoader(update_area) {
    update_area.ajaxStart(function() {
        update_area.show();
        $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
    });
}

## other_file.js
$(function(){
    update_area = $('#someDiv');
    showLoader(update_area);
});

$(function(){some_code;}) is a jQuery shortcut. It tells jQuery to run that code when the document finished loading.

piquadrat
Thanks for this -- I believe this is the answer I'd wanted.
Steve K
+2  A: 

It might be better to write a plugin:

// default.js
$.fn.showLoader = function() {
    this.ajaxStart(function() {
        this.show();
        $(this).html('<img id="loading" src="images/loading.gif" alt="loading" />');
    });
};


// other_file.js
$(function() {
    $('#someDiv').showLoader();
});
Darin Dimitrov
+2  A: 

The issue is not that you have multiple files, but that javascript has function scope, meaning that if you define something (including another function, as you did with showLoading) within a function, it will only be available inside of that function.

function callMe() {
    var foo = 'bar';
    foo; // is 'bar'
}

foo; // is undefined


function callMe() {
    function foo() {}
    foo; // is a function
}
foo; // undefined
Prestaul