Javascript one function name in multiple files

What I need is pretty simple, although I don't know if possible..

I'm attaching all my event handlers to the object themselves instead of to $(document).

But, I need to attach them on the .ready() method, to make sure the object is created before the handler is attached. Since there are a lot of handlers to attach, to keep my code cleaner I want to create a function called attachHandlers() that will be called on document.ready().

But.. this function should execute codes that are in multiple files.

My question is.. is there a way of declaring the same function multiple times, and then calling it just once to execute them all?

Answers 1

  • But.. this function should execute codes that are in multiple files.

    My question is.. is there a way of declaring the same function multiple times, and then calling it just once to execute them all?

    If interpret Question correctly, you want to request javascript from multiple files at .ready() . You can create an array containing url of file to request, use $.when(), $.map(), $.getScript() to call the javascript within the files

    jQuery.getScript( url [, success ] ) Returns: jqXHR
    Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.

    The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page.

    $(document).ready(function() {

      var files = ["1.js", "2.js", "3.js"];
    
      $.when.apply($, $.map(files, function(file) {
        // request file
        return $.getScript(file)
      }))
      .then(function() {
        // complete
        // do stuff
      }, function err(jqxhr, textStatus, errorThrown) {
        // handle error
      });
    
    });
    

Related Articles