How to Easily Create a JavaScript Framework, Part 4

October 25th, 2009 by Teylor Feliz How to Easily Create a JavaScript Framework, Part 4

In “How to Easily Create a JavaScript Framework, Part 3,” we discussed “Waiting Until the DOM Loaded”, “How to Modify “setStyle()”, “Set and Get Values from Input Elements”, and “Fun Effects: “fadeIn()” and “fadeOut().” In this week’s post, I will complete the “VOZ” JavaScript Framework tutorial series, and I will add a few new methods for dealing with a JavaScript Framework. Moreover, I will introduce some AJAX into the Framework. Feel free to use this Framework as you see fit, or to add your own methods. I hope you find the final installment of my series as interesting as the first three! Please remember to comment, and Enjoy!

What is on Topic for Today?

  1. Unbind Events
  2. $$.getByInstance() method
  3. InnerHTML Method
  4. Text Method
  5. AJAX

1. Unbind Events with “UN”

With this method, we are going to do the opposite of the “ON” method that is used to add events to the elements. Instead, now with the “UN” method, we can delete events from our elements. For Example:

//Unbind events from the elements
//E.g $$.getById('elem').un('click',alertme);
un:function(action,callback){
	//Check if the method removeEventListener is available 	
	//This work for all major browsers except IE
	  if(this.elems[0].removeEventListener){
     	for(var i = 0;i < this.elems.length;i++){
	//Remove the event from the elements
      	this.elems[i].removeEventListener(action,callback,false);    
     }
  }
  //If it is IE :( use detachEvent method
  else 
  {
     for(var i = 0;i < this.elems.length;i++){
	 	//Remove the event from the elements, only IE
         this.elems[i].detachEvent('on'+action,callback);
     }
  }
  return this;
}

2. $$.getByInstance() Method

With this method, we only need to save the Object of the element into the framework, in order to work with it. As all the other post, the description of this method is in the code below. For Example:

//Get Elements By Instance
//if you refer to the body of the document, then you should use document.body instead of document
getByInstance:function(elem){
	var elems = [];
    elems.push(elem);
    this.elems = elems;
  return this;
}

3. InnerHTML method

This method is the same as innerHTML method, but with this method we can insert HTML code into the elements found. For Example:

//Method innerHTML to insert HTML code into an element
//html is the param with the html code to insert in the elements
innerHTML:function(html){
	for(var i = 0;i < this.elems.length;i++){
     this.elems[i].innerHTML= html;
  }
  return this;
}

4. Text Method

This method is another way to embed text into the DOM; however, be aware that it will replace the previous content of the element. I find this method very useful in my work. See below for an example:

//Insert text into an element
//Replacing the previous content
text:function(text){
	 text = document.createTextNode(text);
    for(var i = 0; i < this.elems.length;i++){
  	 this.elems[i].innerHTML = '';
     this.elems[i].appendChild(text);
  }
  return this;
}

5. AJAX Object

Here we go. Now lets create an Object to deal with GET/POST requests in AJAX. The object only has two methods. The first method is "getxhr()" used to get an XMLHttpRequest without worrying about the browser. We are limiting with range from IE6 or higher. And the other method is "sendRequest()," which is the one that we are going to use to create an AJAX request. Let's create the AJAX object inside the "VOZ" framework in order to use it like this: "$$.AJAX.method." You can take the AJAX object out of the framework for your own use and it should work fine.

AJAX:{}

a. getxhr Method

This method is created especially for the developer that does not want to use the AJAX framework and prefers to create their own request. This method will just return the XMLHttpRequest Object. For Example:

//This method create an XHR Object
	//If you want to create your own AJAX request just call it
	//E.g. var myXHR = $$.AJAX.getxhr();
 	getxhr:function(){
		var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
		return xhr;
	}

Now we have the way to create a cross browser xhr object. Lets use it in the "sendRequest" method.

b. "sendRequest" Method

"sendRequest" Method can be used for both, GET and POST request. We just need to specify it in one of the parameters. For Example:

//Parameters sendRequest(method, url, ValuesToSend, callbackObject)

Using the Object is pretty easy:

$$.AJAX.sendRequest('post','contact.php',{name:'Al',email:'pacino@mail.com', message:'Hello world'},{success:function(x){alert(x.responseText)}});

The last argument is an object where you can use three different methods:

Success: When the request is satisfactory. Loading: It runs after we send the request and before we receive the answer from the server. And, Error: If there is error of any kind while the request is sending.

	//Main AJAX Method
	//Parameters sendRequest(method, url, ValuesToSend, callbackObject)
	//E.g. $$.AJAX.sendRequest('get','customers.php',{customerId:1234, name:'James', lastname:'Bond'}, {success:function(){alert('yes')}, loading:function(){alert('Waiting')}, error:function(){alert('no')}});
	sendRequest:function(m,url,valObj,callObj){
		//Here we create the xhr Object
		var myxhr = this.getxhr();
		//Because we have to send the values in a query string E.g. myurl.php?param1=value1&param2=value2...
		//We create the var values that is going to save the query string
		//Walking throught the object valObj we take the name and its value
		//Using encodeURLComponent to scape special values
		var values ='?';
		for(var k in valObj){
			values+= encodeURIComponent(k) + '=' + encodeURIComponent(valObj[k]) + '&';
 		}
		//If the method we choose is get we add the values to the url
		//As we don't need to send the values by the xhr.send, we set the variable values to null; 
		if(m === 'get'){
			url+=values;
			values= null;
		}
		//Here opening the AJAX conection
		myxhr.open(m,url,true);
 
		//If the method is post
		//We need to delte the ? at the begining of the string in values;
		//And set the headers requiered for the post method
		if(m=='post'){
			values=values.substring(1,values.length-1);
			myxhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}
		//Send the request with ajax;
		myxhr.send(values);
		//If it is available execute the loading function from the callObj
		if(callObj.loading){ callObj.loading();}
		//When readyState change to 4
		myxhr.onreadystatechange = function(){
			if(myxhr.readyState==4){
				switch(myxhr.status){
					//If estatus is 200 means it success, the execute success from the callObj.
					case 200: if(callObj.success)callObj.success(myxhr); break;
					//If estatus is 403, 404 or 503 means that there is something wrong, execute error from the callObj.
					case 403, 404, 503 :  if(callObj.error)callObj.error(myxhr); break;
					default:  callObj.error(myxhr);
				}
			}
		}
	}

VOZ JavaScript Framework Part 4 Examples

VOZ 4 JS

Please visit the above link in order to view this final part of our "VOZ" framework put into action! Also, stay tuned for future JavaScript and AJAX tutorials, which I am currently working on and hope to have out in the next few months. I hope you found this tutorial enjoyable and easy to follow! Please feel free to comment, because as always I love to hear from web lovers!




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.



Subscribe to our RSS
Please help us to promote this article.
  • How to Easily Create a JavaScript Framework, Part 4
  • Delicious

Tags: , , , ,

Comments 13

  1. slier says:

    finaly..sigh thanks

  2. JavaScript Countdown Timer says:

    very good tut, thank you very much for sharing.

  3. favSHARE says:

    This article has been shared on favSHARE.net. Go and vote it!

  4. Pramod says:

    One of the awesome tutorial for the Advanced JS I have ever seen. Thanks a lot

  5. Admin says:

    @slier, I know you are releived that the article is finally posted! I know you have been waiting awhile. Hope you enjoyed it!

    @JavaScript Countdown Timer, Thanks for the comment. Hope you found the tutorial useful.

    @Pramod, Thank you kindly for that humbling comment! I makes me happy to hear that you found the Framework interesting and educational. Thanks again!

  6. clippingimages says:

    Awesome post :) . Thanks for sharing this nice post.

  7. slier says:

    Thank you teylor feliz for all ur work
    Im really appreciate it

    But i hope u can do a tutorial on css selector engine if u can

    A simple one might do ass an addiotion to ur framework…

    Btw thanks again

  8. dani says:

    nice work!

    It would be nice to change the call $$.getById(‘id’) to just use $$(‘id’) and integrate both the ability to look by the elementId and elementName . This would help in minimizing the code and be similar to JQuery/prototype.

    Thanks for the education

  9. James Brooks says:

    If you’re not bothered about the AJAX method returning an object, and would just like the data from the requested page, you can change:
    case 200: if(callObj.success)callObj.success(myxhr); break;
    to…:
    case 200: if(callObj.success)callObj.success(myxhr.responseText); break;

    James

  10. Antonio says:

    Hello. Thank you very much, great tutorial.

    Actually I’d like to implement a lightweight framework for my personal website, using just the functions and methods you explained, wih maybe 2 or 3 more, but I’d like to know if which license you’re releasing your work under. May I use it as it is and just complete it? And which license would be acceptable for you?
    Thanks.
    Antonio

    • admin says:

      @Antonio

      You can use the code as you want . But I strongly recommend JQuery or any other framework that is being tested hundreds of time. In addition, I just made this tutorial for beginners, for example, instead of create an EACH to use in all the loops, I prefer to use the loop for in all the methods because people can copy and paste in their code. Also, I do not create a new instance of the $$ every time the $$() is call which would be the ideal in a case of an Framework.

      Thanks for visit the site and any question just email me or leave a comment. :)

  11. Antonio says:

    Thank you very much for your reply.
    I tried using jQuery for my website, and I liked it, but I’d prefer a lighter framework, and the idea of a 6K-minified one with just what I want suits me more ;) I tried also midori.js (nice, but I had some problems with some functions and it has more than what I need) and simplejs (even nicer, but also with some strange bugs).

    I like to know the license before use other people’s code, and after your reply I can try and implement the 2 or maybe 3 functions I’ll need, and also modify it someway. As it is so short (and explained ;) , I think I will understand it better than jQuery’s code. And as I’m a Javascript beginner, it will be a good gym, don’t you think?

    Thank you very much again.

    Antonio



Quantcast tag -->