Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,158,283 members, 7,836,259 topics. Date: Wednesday, 22 May 2024 at 12:57 AM

Learning Jquery The Javascript Library - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Learning Jquery The Javascript Library (1078 Views)

Tutorial: Building A Facebook Chat With Jquery/php / Free Jquery Mb.menu / Dhtml Datagrid Control :: Jquery Integration :: Cms Support (2) (3) (4)

(1) (Reply)

Learning Jquery The Javascript Library by cdeveloper(m): 1:28pm On Mar 30, 2009
jQuery is perhaps one of the most popular ,powerful ,light-weight and easy to use javascript framework or library that i have found on the internet and not only can you use the library, you can also extend the library yourself by writing what is call a plugin. A lot of developers have written powerful plugins for this library and i must commend them a lot for their free contribution to the development of the library. I was a bit reluctant initially when i started out with the library because i could not make sense of what it was and besides I DID NOT WANT ANY NEW LIBRARY THAT WOULD MAKE ME FORGET WHAT I ALREADY KNOW ABOUT JAVASCRIPT. Alot of you perhaps are feeling this way now but i must say that getting to know about the library has revolutionized my JS coding and today i have used the knowledge extensively on the ABU Administrative Online Portal Backend. Some of this i have shared on my blog http://www.youbanize.com.
I am not going to bore you with theories but i will start off on a practical way,since they say that the best way to learn programming is by example; also i will reference other sites for more advanced usage of this simple but powerful library. The jQuery magic starts with this:
$(document).ready(function(){
//the codes goes here
});
or
jQuery(document).ready(function(){
//the code goes here
});

The dollar sign ($) is a shorthand notation for the jQuery object and they can be used interchangeably.

How to i get started with jQuery Library?
The first thing you will do is to get the latest version of the library from google code site www.code.google.com; it is now been hosted their
include it on a simple page as you would any javascript file and then in the header section of your page include this script

<script type='text/javascript' src='jquery-the.version.you.are.using.js'></script>
<script type='text/javascript'>

alert("The dimension of your browser are : Width::"+$(document).width()+" and the height is ::"+$(document).height());
</script>


The above code will output the dimensions of your current browser when the page has fully loaded.
I will continue the exploring of jQuery and what it has in store for developers who wish to take advantage of the power of jQuery. Just to wet your appetite, did you no that you can create those effect you see on Facebook with jQuery? Well i have done it and perhaps you will get to see it some day.
For those who want get the hands on it just post your questions here so that others can benefit too or post it on my blog www.youbanize.com.
i am christian an Open Source Developer.
Re: Learning Jquery The Javascript Library by Nobody: 7:19am On Apr 04, 2009
I thought u are here to give us a tutorial, but rather advertising a blog. . .
Re: Learning Jquery The Javascript Library by cdeveloper(m): 4:45pm On Apr 20, 2009
You are right dhtml, yet i do not see anything wrong in showing those who are interested some of the articles i have written about jQuery. I think it is one of the principles of programming DRY ( Do not Repeat Yourself)
So Today i will be looking out something very important that i have always thought is only done on the serverside,yet it could be done on the clientside
i use to write serverside caching systems and it did work fine until lately i started looking at sites like google Map. I realize that both Gmail and Google Map and not just mere application but are also very intelligent applications too. One aspect i took time to look at is the way GMap cache on the client side giving you that feeling that you are using a desktop App. Well google map uses a mixture of Predictive  and Passive Cache Pattern to get the job done. Passive Cache is a method caching in which your previous request are cached on the clientside so that when you request the same information again that data is not polled from the server but from the cache. This form of cache only changes whenever there is a change in the data itself.While Predictive Cache is a method that simply predict what you might do next based on previous requests. For instance if you are reading an article that spans multiple pages and you are current viewing page 1 the Predictive Cache figures that since you are reading page1 there is a 50 05 chance of reading Page 2 so it downloads it at the background using a AJAX and cache it so that when you eventual clicks on Page 2 it just loads as though you are working on a Desktop App. Well those are the ways Caching on the clientside are done i am going to show an implementation of clientside cache that can work for both method of caching, since all we need is a data store on the clientside with ability to update, delete, insert and do periodic update on the data.
So How do we Implement A Clientside Cache Using jQuery?

The implementation of a clientside cache using jQuery is simple, first we need to define the structure of our cache, for this i will use a simple Javascript Object for that them i will define methods for Adding ,Deleting,Garbarge Collecting and Updating data on the cache Object. So lets start by defining the cache Data Structure. I will be usoing OOP design here so that i can pack both Data and methods that work on the data into the same JavaScript Class( Did i say class in JS impossible there is no class structure in JS some of you will say but people have learned to implement concept in OOP language also in JavaScript) will show how to in the process of building this object

What does a simple class look like in JavaScript?

Cache={};

That is what a class look like in JavaScript even though it does not yet have properties and methods. There are other ways on implement classes in JS using prototype property of javascript object i will be using the one the template above
So a Cache object will need methods like Update,Add,Remove,GC(Garbage Collector) and of course the init Method and a data store
Cache class will look like this

Cache={
  cache:{},
init:function()
      {

      },
update:function(data)
            {

            },
remove:function(data)
            {

            },
add:function(data)
      {

       },

gc:function()
    {}
};


I suppose the class is beginning to make sense with those methods studs  and the cache data store added i have called the data store cache and it is an object literal,you will see why it have to be an object literal. Now we need one more stuff here. We need away to tell the GC that a piece of data has expired, so we need to set an expiry date for each data item in the cache so that the gc can use that to determine which data item needs to be cleared. So we will add a second property call livetime to the class so our evolving class will look like this

Cache={
  cache:{},
  livetime:60000,
init:function()
      {

      },
update:function(key,val)
            {

            },
remove:function(key,val)
            {

            },
add:function(key,val)
      {

       },

gc:function()
    {}
};

I have initialize the livetime property to 60 seconds(1 minute),by the way a seconds is 1000 micro-seconds in JS so 60000 ms = 60 s.
We will define the add method which adds data to the cache store. Now the cache is an object literal because it needs to store data in the form of Key/Value pair so that we can access specific data item using the key. The value itself is an Object as well because for each value stored we need to store the time that data item is stored so that the gc can check it at interval to determine if the data value is still valid or not. Enough theory the code below

Cache={
  cache:{},
init:function()
      {

      },
update:function(key,val)
            {

            },
remove:function(key)
            {

            },
add:function(key,val)
      {
         
          var lt=new Date();
           if(Cache.cache[key]!=null)
            {
               Cache.update(key,val);
            }else
             {
                   Cache.cache[key]={value:val,timestamp:lt.getTime()};       
             }       
       },

gc:function()
    {}
};

And that is what the add method looks like if the key already exists it is updated , else it is added to the cache.Also not the timestamp property added to the data object this will be compared to the livetime to determine the validity of that data. the method getTime() returns the current timestamp in microseconds
Next i will implement the update method

Cache={
  cache:{},
init:function()
      {

      },
update:function(key,val)
            {
               var lt=new Date();
                 if(Cache.cache[key]!=null)
                   {
                       Cache.cache[key]={value:val,timestamp:lt.getTime()};
                   }
            },
remove:function(key)
            {

            },
add:function(key,val)
      {
         
          var lt=new Date();
           if(Cache.cache[key]!=null)
            {
               Cache.update(key,val);
            }else
             {
                   Cache.cache[key]={value:val,timestamp:lt.getTime()};       
             }       
       },

gc:function()
    {}
};


Next i will implement the remove method which simply delete a given item from the data store based on a given key

Cache={
  cache:{},
init:function()
      {

      },
update:function(key,val)
            {
                var lt=new Date();
                 if(Cache.cache[key]!=null)
                   {
                       Cache.cache[key]={value:val,timestamp:lt.getTime()};
                   }

            },
remove:function(key)
            {
                 if(Cache.cache[key]!=null)
                {
                   delete (Cache.cache[key]);
                 }
            },
add:function(key,val)
      {
         
          var lt=new Date();
           if(Cache.cache[key]!=null)
            {
               Cache.update(key,val);
            }else
             {
                   Cache.cache[key]={value:val,timestamp:lt.getTime()};       
             }       
       },

gc:function()
    {}
};

Very easy to delete record from the cache using javascript in-built delete command. Next i will implement the most intricate part of the system which is the gc method for garbage collection. If you have worked with OOP language you must have come across GC then. Our GC job is to go through all the data item in store , check the timestamp against the global livetime. if the are expired clear them. How we are goint to do this is to use the compare the current timestamp with the timestamp store for each data item. The implemantation is as shown

Cache={
  cache:{},
init:function()
      {

      },
update:function(key,val)
            {
                var lt=new Date();
                 if(Cache.cache[key]!=null)
                   {
                       Cache.cache[key]={value:val,timestamp:lt.getTime()};
                   }

            },
remove:function(key)
            {
                 if(Cache.cache[key]!=null)
                {
                   delete (Cache.cache[key]);
                 }
            },
add:function(key,val)
      {
         
          var lt=new Date();
           if(Cache.cache[key]!=null)
            {
               Cache.update(key,val);
            }else
             {
                   Cache.cache[key]={value:val,timestamp:lt.getTime()};       
             }       
       },

gc:function()
    {
         var lt=new Date();
          var now=lt.getTime();
           jQuery.each(Cache.cache,function(key){
              var dataitem=Cache.cache[key];
               var ts=dataitem.timestamp;
               
               if(parseInt(now) - parseInt(ts)>Cache.livetime)
                {
                      delete(Cache.cache[key]);
                }
         
         });
    }
};

That was it, using jQuery array iterating method jQuery.each(index,callback), i have looped through all the data items in the cache and removed all tose that are already expired. you will notice that i computed the time difference between the timestamp stored during adding the data item and the current timestamp as at the time the gc method is running. One problem remaining is to make the gc run indefinitely at a specific interval as long as the page has not refreshed yet. This we will implement in the init method of the cache class

Cache={
  cache:{},
init:function()
      {
              setInterval(function(){
                                  Cache.gc();
                                },2000);
      },
update:function(key,val)
            {
                var lt=new Date();
                 if(Cache.cache[key]!=null)
                   {
                       Cache.cache[key]={value:val,timestamp:lt.getTime()};
                   }

            },
remove:function(key)
            {
                 if(Cache.cache[key]!=null)
                {
                   delete (Cache.cache[key]);
                 }
            },
add:function(key,val)
      {
         
          var lt=new Date();
           if(Cache.cache[key]!=null)
            {
               Cache.update(key,val);
            }else
             {
                   Cache.cache[key]={value:val,timestamp:lt.getTime()};       
             }       
       },

gc:function()
    {
         var lt=new Date();
          var now=lt.getTime();
           jQuery.each(Cache.cache,function(key){
              var dataitem=Cache.cache[key];
               var ts=dataitem.timestamp;
               
               if(parseInt(now) - parseInt(ts)>Cache.livetime)
                {
                      delete(Cache.cache[key]);
                }
         
         });
    }
};

So there is the trigger; i have set it to run at an interval of 2 seconds , that is the gc method get called after every 2 seconds to do its Garbage Collection job. I think i am missing something. We have defined how to get data into the cache, update it , and remove it but  i have not yet defined how to get back data from the cache
so i will define that

Cache={
  cache:{},
init:function()
      {
              setInterval(function(){
                                  Cache.gc();
                                },2000);
      },
update:function(key,val)
            {
                var lt=new Date();
                 if(Cache.cache[key]!=null)
                   {
                       Cache.cache[key]={value:val,timestamp:lt.getTime()};
                   }

            },
remove:function(key)
            {
                 if(Cache.cache[key]!=null)
                {
                   delete (Cache.cache[key]);
                 }
            },
add:function(key,val)
      {
         
          var lt=new Date();
           if(Cache.cache[key]!=null)
            {
               Cache.update(key,val);
            }else
             {
                   Cache.cache[key]={value:val,timestamp:lt.getTime()};       
             }       
       },
getItem:function(key)
            {
                if(Cache.cache[key]!=null)
               {
                   return Cache.cache[key].value;
               }else
               {
                   return null;
               }
           },
gc:function()
    {
         var lt=new Date();
          var now=lt.getTime();
           jQuery.each(Cache.cache,function(key){
              var dataitem=Cache.cache[key];
               var ts=dataitem.timestamp;
               
               if(parseInt(now) - parseInt(ts)>Cache.livetime)
                {
                      delete(Cache.cache[key]);
                }
         
         });
    }
};

So the getItem simply checks if the data item requests exists in the cache. if does exists it is returned else for now it will return null but in a prodcutive environment, this is the place to use Ajax to fetch the data from the server, put it in the cache and then return the data to the caller method. So far i have developed Cache simple cache system that can still be improved on.For instance we can make the gc method to refresh all outdated data item from the server without page refresh and the user not beeing aware of what is happening at the background.One more thing still remains, which is initiate the action of periodic update of the cache.
Here i will show how how to do that on page load using jQuery


<head>
<script type='javascript' src='jquery.js'></script>
<script type='javascript' src='path2yourcachescriptfile.js'></script>
<script type='javascript'>
jQuery(document).ready(function(){
//call the init method of the cache system
Cache.init();
});
</script>

</head>


And that is your cache system running , the gc method gets called every 2 seconds and the cache is purged every 2 seconds

(1) (Reply)

How Do I Use Twitter To Market My Products / Need A Webhosting Site / Data On Road Accidents For Nigeria

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 63
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.