Question

(I'm new to javscript and) I want to create a utility class that has access to certain libraries on my webpage. For instance, I currently have D3 and Jquery loaded on my webpage

<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="util.js"></script>

My utility class (utils.js) looks like

(function (window, JQ, D3) {

    function hasWindow(){
        console.log(window);    
    }
    function hasJquery(){
        console.log(JQ);    
    }
    function hasD3(){
        console.log(D3);    
    }
})(this, this.jQuery, this.d3);

I have three questions:

  1. Do I need to pass in the libraries and window to use them within util.js, or will it already have accesss to them?
  2. Once util.js is loaded, how do i call the functions on the utility class (i.e. hasWindow();)?
  3. Am I actually using an appropriate pattern to create a utility class?
Was it helpful?

Solution

Providing all are loaded into the page, you can access the other libraries from within your own.

It's a good idea to wait until after the page has finished loading too. You can do that in JQuery using $(function(){ ... });

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top