Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and implement a custom JavaScript library

I am new to javaScript and am unsure how to go about creating a new js library and referencing this in another js file.

If I have a standalone file Utilities.js

var Utilities= 
{
   show: function(input)
   {
      alert(input);
   }
};

Am I missing something as to how a library should be defined standalone?

My second question is how to use that is sub-sequent js files. What I did so far is:

<script type="text/javascript" src="resources/Utilities.js"></script>

In my index.html. Is this enough to reference it as:

Utilities.show("Hello");

In any other java script file?

I tested it in this fashion and got and error "Utilities is not defined"

NOTE: This is just an example and not my full and practical purpose.

like image 873
cain4355 Avatar asked Jan 08 '23 02:01

cain4355


2 Answers

Yes, including that Javascript file with that global variable declared is enough to call your methods this way Utilities.show("Hello"); from another Javascript file loaded after Utilities.js or inside a <script></script> section of your html.

But you can actually improve it a little, following the module pattern and exposing only the functions you really need to the global scope (you'll likely write some functions that the users of your library should not call directly, this allows you to do it in a clean way):

var Utilities=Utilities||(function () {

   //Accessible only here
   var privateArray=[];

   //Cannot be called from outside this function
   var privateFunction=function(){
   }

   //Return only what must be publicly accessible, in this
   //case only the show() method
   return {
      show: function(input){
         privateFunction();
         alert(input);
      }
   }
})();

That (function () { /* Code */})();, defining a new scope for your code will also avoid name clashes with other global javascript object/functions.

like image 115
uraimo Avatar answered Jan 10 '23 17:01

uraimo


  1. It is OK to use object literals, but you can define libraries using other patterns (module, revealing module, constructors, etc).

I recommend these links to understand primitives, scopes, closures, object literals, etc.

http://bonsaiden.github.io/JavaScript-Garden/

http://jsbooks.revolunet.com/

  1. To call the method inside index.html you need to add a tag.

    <script> Utilities.show("Hello"); </script>

But this approach it's not recommended. Instead of it, you can create a new JS file to run your library code.

<script type="text/javascript" src="resources/Utilities.js"></script> <script type="text/javascript" src="resources/main.js"></script>

In main.js

Utilities.show("Hello");

Hope it helps.

like image 27
jandrade Avatar answered Jan 10 '23 15:01

jandrade