How to Easily Create a JavaScript Framework, Part 1

May 20th, 2009 by Teylor Feliz

vozframework

Currently, JavaScript is the one of the most utilized and popular programming language, because a large majority of the browsers are compatible with it and make use of it. Therefore, JavaScript has become very popular, very fast, because it is so uncomplicated, straightforward, and has a wide-range of capabilities. Nearly all programmers used to think that JavaScript was a toy language, but the emergence of AJAX into the market manifested something completely to the contrary, because it showed JavaScript diverse capabilities and functionalities. Since this discovery, programmers can create web applications that give the impression of desk top application, which is helpful because data can be changed more quickly.

However, the use of DOM in the browsers, such as Internet Explorer, makes it difficult to work with JavaScript at times. Consequently, that is why JavaScript frameworks are now exploding onto the market, in order to make cross browser scripting possible. Popular JavaScript frameworks like Prototype, JQuery, YUI, and Dojo have been used for the last five years by many programmers around the world to create amazing web applications. Now, I am going to take you step by step to create a JavaScript framework, walking through the DOM simple effects and AJAX utilities. Hopefully, you can take this information and learn to implement it yourself.

What is on topic for today?

  1. Avoiding Global Variables
  2. Creating a Main Object/Framework
  3. DOM Navigation Part 1
  4. Chaining Methods

1. Avoiding Global Variables

Before we start creating the VOZ framework, we should know that we have to avoid global variables in all pages because JavaScript uses the last variable declaration with its value without warning that we declared it in a sentence before. For example:

var x = 23; //Declare and use the x variable assigning 23 as value;
var x = 44; //Assign 44 to the variable without warning that our variable is already declared
x;  //The actual value is 44

A good method to avoid global variables is creating a anonymous function that keeps our variable inside the function scope. For example:

(function(){

//Variables and functions go here.

})();

Anonymous functions are very useful when we are working with JavaScript Frameworks, because we can pass them as value to our functions. We will see that later.

2. Creating a Main Object/Framework

It is well known that JavaScript has two ways to create objects: Constructor Functions and Literal Objects.

Constructor functions:

//Defining the Object/Class User with two parameters “name and lastname”.
function User(name, lastname){
	this.name = name;
	this.lastName = lastname;
}
//To use the User Object/Class with new
var myUser = new User(‘Carl’,’Anderson’);
myUser.name // It returns “Carl”

Literal Object:

The second way and the most recommended by experts like Douglas Crockford is the Literal Object. This style is what we are going to use to create our Framework, because it is the most elegant and efficient way to create objects. For example:

myUser = {
	name: ‘Carl’,
   lastName: ‘Anderson’
};
myUser.name //Returns “Carl”

Well, enough with theories, let’s put this into action and create our Framework. First, select a short, attractive name for your framework. For this example, I will use the name “VOZ.” For example:

// Wrapping my framework to avoid unpredictable errors with others frameworks and variables.
(function (){
//Creating our framework named VOZ
var VOZ = {}
})();

Now we have our framework ready but we need to create some a property and some methods. For now we are going to add “getById,” “addClass,” and “ON” methods.

(function(){

var VOZ = {
//The elems array is going to contains all the elements in order to chain
elems :[],
//The method to get Elements By Id
getById:function(){},
//Method to add a CSS Class
addClass:function(){},
//Method to add an event to our Elements
on:function(){},
//Add text into an element
appendText:function(){}
//Show/Hide
toggleHide:function(){}
}
})() ;

Literal Object:

3. DOM Navigation Part 1

Walking trough the DOM is vital for a Javascript programmer, because that gives you the ability to modify, delete, or add new elements in an specific place of the web page.

The method for now is “getById;” however, this is not the normal “document.getElementById” method, because this takes more than one parameter to find the elements by their ID. For example:

              //Get all elements by Id
                //It could take more than one parameter
                getById:function(){
                            var tempElems = []; //temp Array to save the elements found
                            for(var i = 0; i < arguments.length;i++){
                                if(typeof arguments[i] === 'string'){ //Verify if the parameter is an string
                                    tempElems.push(document.getElementById(arguments[i])); //Add the element to tempElems
                                }
                            }
                            this.elems = tempElems; //All the elements are copied to the property named elems
                            return this; //Return this in order to chain
                        },

We have a method to find elements by ID, but let’s create the next method that adds a class name to our elements, called “addClass”:

               //Add a new class to the elements
                //This does not delete the all class, it just add a new one
                addClass:function(name){
                    for(var i = 0;i < this.elems.length;i++){
                                this.elems[i].className += ' ' + name; //Here is where we add the new class
                            }
                            return this; //Return this in order to chain
                },

The last method for today is "ON," that is used to add events in our elements, e.g. 'click', 'mouseover','mouseout', etc.

//Add an Event to the elements found by the methods: getById and getByClass
                //--Action is the event type like 'click','mouseover','mouseout',etc
                //--Callback is the function to run when the event is triggered
                 on: function(action, callback){
                           if(this.elems[0].addEventListener){
                                for(var i = 0; i < this.elems.length;i++){
                                    this.elems[i].addEventListener(action,callback,false);//Adding the event by the W3C for Firefox, Safari, Opera...
                                }
                            }
                           else if(this.elems[0].attachEvent){
                                    for(var i = 0; i < this.elems.length;i++){
                                        this.elems[i].attachEvent('on'+action,callback);//Adding the event to Internet Explorer :(
                                    }
                            }
                            return this;//Return this in order to chain
                        },

To attach text into our elements, we can use this method:

//Append Text into the elements
            //Text is the string to insert
            appendText:function(text){
                                    text = document.createTextNode(text); //Create a new Text Node with the string supplied
                                    for(var i = 0; i < this.elems.length;i++){
                                    this.elems[i].appendChild(text);//Append the text into the element
                                    }
                                    return this;//Return this in order to chain
                        },

To show/hide the elements found, we use this method:

 //Show and Hide the elements found
            toggleHide:function(){
                            for(var i = 0; i < this.elems.length;i++){
                            this.elems[i].style['display'] = (this.elems[i].style['display']==='none' || '') ?'block':'none'; //Check the status of the element to know if it could be displayed or hided

                            }
                            return this;//Return this in order to chain
                        }

Lastly, let's add this at the end of the object:

if(!window.$$){window.$$=VOZ;}//We create a shortcut for our framework, we can call the methods by $$.method();

This is to use our framework with the $$ like shortcut. For example:

$$.getById('myElement')

Now our framework looks like this:

(function(){
           var VOZ = {
            elems:[],//Array to save all the elements found by the functions getById, getByC

                //Get all elements by Id
                //It could take more than one parameter
                getById:function(){
                            var tempElems = []; //temp Array to save the elements found
                            for(var i = 0;i < arguments.length;i++){
                                if(typeof arguments[i] === 'string'){ //Verify if the parameter is an string
                                    tempElems.push(document.getElementById(arguments[i])); //Add the element to tempElems
                                }
                            }
                            this.elems = tempElems; //All the elements are copied to the property named elems
                            return this; //Return this in order to chain
                        },

                //Add a new class to the elements
                //This does not delete the all class, it just add a new one
                addClass:function(name){
                    for(var i = 0; i < this.elems.length;i++){
                                this.elems[i].className += ' ' + name; //Here is where we add the new class
                            }
                            return this; //Return this in order to chain
                },

                //Add an Event to the elements found by the methods: getById and getByClass
                //--Action is the event type like 'click','mouseover','mouseout',etc
                //--Callback is the function to run when the event is triggered
                 on: function(action, callback){
                           if(this.elems[0].addEventListener){
                                for(var i = 0; i < this.elems.length;i++){
                                    this.elems[i].addEventListener(action,callback,false);//Adding the event by the W3C for Firefox, Safari, Opera...
                                }
                            }
                           else if(this.elems[0].attachEvent){
                                    for(var i = 0;i < this.elems.length;i++){
                                        this.elems[i].attachEvent('on'+action,callback);//Adding the event to Internet Explorer :(
                                    }
                            }
                            return this;//Return this in order to chain
                        },

            //Append Text into the elements
            //Text is the string to insert
            appendText:function(text){
                                    text = document.createTextNode(text); //Create a new Text Node with the string supplied
                                    for(var i = 0; i < this.elems.length;i++){
                                    this.elems[i].appendChild(text);//Append the text into the element
                                    }
                                    return this;//Return this in order to chain
                        },

            //Show and Hide the elements found
            toggleHide:function(){
                            for(var i = 0; i < this.elems.length;i++){
                            this.elems[i].style['display'] = (this.elems[i].style['display']==='none' || '') ?'block':'none'; //Check the status of the element to know if it could be displayed or hided

                            }
                            return this;//Return this in order to chain
                        }

    }
    if(!window.$$){window.$$=VOZ;}//We create a shortcut for our framework, we can call the methods by $$.method();
          })();

4. Chaining

Chaining is the ability to call methods together. This makes your code more understandable and organized.

Without Chaining

$('#element').method1();
$('#element').method2();
$('#element').method3();

With Chaining

$('#element').method1().method2().method3();

VOZ JavaScript Framework Example

Please visit the above link in order to view the first part of our VOZ framework put into action! Also, stay tuned for the second part of this post, which is in the works! I hope you enjoyed reading this tutorial and found it easy to follow! Please feel free to comment, as I love to hear from fellow developers!


Teylor Feliz is a well-known XHTML/CSS/JavaScript enthusiast from Santo Domingo, Dominican Republic. He has more than 10 years experience in the computer programming and development world, including 2 years teaching computer science. He is currently living in Louisiana, where he plans to complete his degree in Computer Science, and begin a Masters in the field.


       Delicious
Tags: , ,

Comments 18

  1. JavaScriptBank.com says:

    very very cool & good article, thank you very much for sharing.

    When you complete this framework, can you share it on my JavaScript site, http://javascriptbank.com/submit/ ?

    Thank

  2. joyoge designers' bookmark says:

    great tutorial thank you..

  3. admin says:

    Thanks everyone for the comments! Stay tuned for Part 2 in the next week or so!

  4. msikwal says:

    grt artical …thanks…

  5. slier says:

    i been lurking all around the web top found tutorial on how to create javascript framework..thank god i found ur site

    its easily foloow and understandable..keep up a good work

  6. admin says:

    Great! I am glad you found the tutorial useful! I will be coming out with parts three and four soon! Keep checking back! Thanks.

  7. slier says:

    sure i keep checking this site daily to know if there is any update on this tutorial..big thanks bro

  8. slier says:

    in ur example page,i see u intilize the whole libarray using window.onload event..is this a good approach?

    can u achive something like jQuery read() method?

    $(document).ready(function(){
    //do stuff
    })

  9. slier says:

    i think the code for initilize ur library should not be in window.onload function
    cause ur libarary is self invoking function and then register the VOZ object to global $$ variable

    correct me if im wrong

    view-source:http://admixweb.com/downloads/vozframework/vozpart1.html

    • admin says:

      Yes, you are 100% right, but I want people not to care about the window.onload before we talk about the domReady function. I just put all the code inside of the window.onload = function(){..code here..} because it looks less complicated. Does that explain your question?

  10. slier says:

    Yes u did

    i just want to clarify that cause i myself not very familiar with javscript since im come from php background

    thanks to you now i have learn so many thing in javascript

  11. slier says:

    so is there any news about part 3 and part 4 ??

    cant wait on it

  12. slier says:

    Good to hear that…

    Thanks admin

  13. sky says:

    yes part 2, 3, 4 soon please

  14. Debt Settlement Program says:

    punctilious post. simply one detail where I contest with it. I am emailing you in detail.

  15. zhaiduo says:

    Great tutorial! Thanks!

  16. kidi says:

    Greate job!



VDK.com.do JTutorials