Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, August 5, 2012

Javascript Anonymous Functions And The Module Pattern

One of the most annoying things about JavaScript is that it has no scope for variables. Any variable, function, array or object you define that is not inside another function is global, which means that other scripts on the same page can access—and will usually override— them.
The workaround is to encapsulate your variables in an anonymous function and call that function immediately after you define it. For example, the following definition would result in three global variables and two global functions:

var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
  // [...]
}
function getMemberDetails(){
  // [...]
}

Any other script on the page that has a variable named status could cause trouble. If we wrap all of this in a name such as myApplication, then we work around that issue:

 var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
}();
This, however, doesn't do anything outside of that function. If this is what you need, then great. You may as well discard the name then:

  (function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
})();
If you need to make some of the things reachable to the outside, then you need to change this. In order to reach createMember() or getMemberDetails(), you need to return them to the outside world to make them properties of myApplication:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  return{
    createMember:function(){
      // [...]
    },
    getMemberDetails:function(){
      // [...]
    }
  }
}();
// myApplication.createMember() and 
// myApplication.getMemberDetails() now works.


This is called a module pattern or singleton. It was mentioned a lot by Douglas Crockford and is used very much in the Yahoo User Interface Library YUI. What ails me about this is that I need to switch syntaxes to make functions or variables available to the outside world. Furthermore, if I want to call one method from another, I have to call it preceded by the myApplication name. So instead, I prefer simply to return pointers to the elements that I want to make public. This even allows me to shorten the names for outside use:

 var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
  return{
    create:createMember,
    get:getMemberDetails
  }
}();
//myApplication.get() and myApplication.create() now work.

Reffer: "revealing module pattern."
http://coding.smashingmagazine.com/2010/04/20/seven-javascript-things-i-wish-i-knew-much-earlier-in-my-career/

Wednesday, July 25, 2012

Working With Cookies In Javascript

Cookies are variables of temporary data which is stored on the visitors computers. They are normally used for things like remember my username on a login form. This can be a useful way to store information about your returned visitors without them having to log in to store information on a database.

It's worth noting that cookies should not be used to store secure information as they are just files stored on your visitors computer.

You can set a cookie on both the server side and the client side in this article we are going to look at the process you would set-up a cookie on the client side using Javascript.

Raw Javascript

Working with cookies in Javascript is not the best feature of Javascript, there is no easy way of dealing with setting and getting cookies.

All Values

To get all the cookies which are set for the current document you need to use the following.
                var allCookies = document.cookie;
            

Setting Values In Javascript

To set a cookie you need to use the Javascript variable document.cookie, to add values to this you need to setup the data as a query string and add onto the end of the document.cookie.
document.cookie = "website=weblink";
// cookie is website=weblink

If you want to add extra data to the cookie then you just need to repeat the above step.
document.cookie = "secondwebsite=second-site-demo";
// cookie is website=weblink;secondwebsite=second-site-demo;

Now this seems easy to set data but this will not deal with expiring the cookie or domain for the cookie. To set the expiry of the cookie you need to add the expiry on the end of the document.cookie.
document.cookie += "; expires="+date.toGMTString();

To set the domain path of the cookie you then need to set the path on the end of the document.cookie.
            document.cookie += "; path=/";
        

With these factors you can add to just setting data on the cookie it can be difficult to handle you need to write a function to handle the setting of the cookie.
function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

Getting Values

As you can see there is a lot you need to do to set the values on the document.cookie but you will need to do even more to get values out of the document.cookie.
If you want to get a certain value you have set you can't just call the key of the data to get the value you have to use a function which will do a reg ex search to get the value of a key.

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

Easier Way Of Working With Cookies In Javascript

There must be an easier way of handling the cookie data then having to create you own functions to deal with the different scenarios of setting, getting, all cookies, remove cookies, empty all cookies, testing if cookies are enabled.
There is an easier way of working with cookies there is a Github project called cookie.js, this is a simple javascript file which when included on your web page you can easily handle the cookie data.

Cookie.js

To use cookie.js all you have to do is download it from Github and include it on your page, download it from here. Then you can include it on the page by doing using the following code.

            <script src="cookie.min.js" > </script >
        

When this file is included there will be a new cookie object to use to set and get the data.

Setting Cookie

To set a cookie with cookie.js all you have to do is use the method set().

cookie.set( 'key', 'value' );

If you want to add extra parameters to the cookie you can set these up as the third argument on the method.
cookie.set( 'key' , 'value', {
   expires: 7,
   domain: "paulund.co.uk",
   path: "/",
   secure: false
});

Getting Cookie

To get the values from the cookie it is as easy as using the get() method, this will return string of the value of the key.

cookie.get( 'key1' );

Or you can even use a shorthand version of this by just doing.
cookie( 'key1' );

Get All Cookies

To get all the cookies available it is very simple by using the all() method.

var allCookies = cookie.all();

Removing Cookies

It is also easy to remove the cookies by referring to the key you have setup on the cookie, by using the remove() method.

cookie.remove( 'key1' );

You can even remove all cookies available on the domain by using the empty method.

cookie.empty();

Cookies Enabled

Visitors can turn cookies off on the browser so you will not be able to store data on the visitors computer, for this reason you will need to check if cookies are enabled before you try setting up new cookies.
With cookie.js you can do this easily by using the enabled() method.

if (cookie.enabled()) {
   // Cookies are on you can setup cookies
} else {
   // Cookies are turned off you can not use cookies
}

ref:http://www.paulund.co.uk/cookies-with-javascript