Introduction to HTTP and REST

0

Category :

A Beginner’s Introduction to HTTP and REST

The HyperText Transfer Protocol (HTTP) is the life of the Web. It’s used every time you transfer a document, or make an AJAX request.

Why REST

REST is a simple way to organize interactions between independent systems with minimal overhead using clients as diverse as mobile phones and other websites. In theory, REST is not tied to the web, but REST is almost always implemented as such, and was inspired by HTTP. As a result, REST can be used wherever HTTP can.

The alternative is building relatively complex conventions on top of HTTP. Often, this takes the shape of entire new XML-based languages. The most illustrious example is SOAP. Because REST has been inspired by HTTP and plays to its strengths, it is the best way to learn how HTTP works.

HTTP

HTTP is the protocol that allows for sending documents back and forth on the Web. A protocol is a set of rules that decide what messages can be exchanged and what messages are appropriate replies to others. Another common protocol is POP3, which you possibly use to fetch email on your hard disk.

In HTTP, there are two different roles: server and client. In general, the client always initiates the conversation; the server replies. HTTP is text based; that is, messages are essentially bits of text, although the message body can also contain other media.

HTTP messages are made of a header and a body. The body can often remain empty; it contains data you want to transmit over the network in order to use it according to the instructions in the header. The header contains metadata, such as encoding information; but, in the case of a request, it also contains the important HTTP methods. In the REST style, you will find that header data is often more significant than the body.

URLs

URLs are how you identify the things that you want to operate on. We say that each URL identifies a resource. These are exactly the same URLs which are assigned to web pages. In fact, a web page is a type of resource.

Resources are best thought of as nouns. For example, the following is not RESTful:

/clients/add

This is because it uses a URL to describe an action. This is a fairly fundamental point in distinguishing RESTful from non-RESTful systems.

Finally, URLs should be as precise as needed; everything needed to uniquely identify a resource should be in the URL. You should not need to include data identifying the resource in the request. This way, URLs act as a complete map of all the data your application handles.

But how do you specify an action? For example, how do you tell that you want a new client record created instead of retrieved? That is where HTTP verbs come into play.


URLs v Requests ???????????????????????????????????

Finally, URLs should be as precise as needed; everything needed to uniquely identify a resource should be in the URL. You should not need to include data identifying the resource in the request.

HTTP Verbs

Each request specifies a certain HTTP verb, or method, in the request header. This is the first all caps word in the request header. For instance,

GET / HTTP/1.1 

HTTP verbs tell the server what to do with the data identified by the URL.


The request can optionally contain additional information in its body, which might be required to perform the operation – for instance, data you want to store with the resource.

If you have ever created HTML forms, you’ll be familiar with two of the most important HTTP verbs: GET and POST. But there are far more HTTP verbs available. The most important ones for building RESTful API are GET, POST, PUT and DELETE. Other methods are available, such as HEAD and OPTIONS, but they are more rare (if you want to know about all other HTTP methods, the official source is IETF).

GET

GET is the simplest type of HTTP request method the one browsers use all the time when you click a link or type a URL in the address bar. It instructs the server to transmit the data identified by the URL to the client. Data should never be modified on the server side as a result of a GET request. In this sense, a GET request is read-only, but of course, once the client receives the data, it is free to do any operation with it on its own side – for instance, format it for display.

PUT

A PUT request is used when you want to create or update the resource identified by the URL. For example,

PUT /clients/robin  

might create a client called Robin on the server. You will notice that REST is completely backend agnostic; there is nothing in the request that informs the server how the data should be created – just that it should. PUT requests contain the data to use in updating or creating the resource in the body.

DELETE

DELETE should perform the contrary of PUT; it should be used when you want to delete the resource identified by the URL of the request.

POST

POST is used when the processing you wish to happen on the server should be repeated, if the POST request is repeated (that is, they are not idempotent; more on that below). In addition, POST requests should cause processing of the request body as a subordinate of the URL you are posting to.

POST /clients/

should not cause the resource at /clients/, itself, to be modified, but a resource whose URL starts with /clients/.

PUT requests are used easily instead of POST requests, and vice versa. Some systems use only one, some use POST for create operations, and PUT for update operations (since with a PUT request you always supply the complete URL), some even use POST for updates and PUT for creates.

Classifying HTTP Methods

Safe and unsafe methods:
safe methods are those that never modify resources. The only safe methods, from the four listed above, is GET. The others are unsafe, because they may result in a modification of the resources.

Idempotent methods:
These methods achieve the same result, no matter how many times the request is repeated: they are GET, PUT, and DELETE. The only non idempotent method is POST. PUT and DELETE being considered idempotent might be surprising, though, it, in fact, is quite easy to explain: repeating a PUT method with exactly the same body should modify a resource in a way that it remains identical to the one described in the previous PUT request: nothing will change! Similarly, it makes no sense to delete a resource twice. It follows that no matter how many times a PUT or DELETE request is repeated, the result should be the same as if it had been done only once.

Remember: it’s you, the programmer, who ultimately decides what happens when a certain HTTP method is used. There is nothing inherent to HTTP implementations that will automatically cause resources to be created, listed, deleted, or updated. You must be careful to apply the HTTP protocol correctly and enforce these semantics yourself.


Representations

We can sum up what we have seen so far in the following way: the HTTP client and the HTTP server exchange information about resources identified by URLs.

We say that the request and response contains a representation of the resource. By representation, we mean information, in a certain format, about the state of the resource or how that state should be in the future. Both the header and the body are part of the representation.

The HTTP headers, which contain metadata, are tightly defined by the HTTP spec; they can only contain plain text, and must be formatted in a certain manner.

The body can contain data in any format, and this is where the power of HTTP truly shines. You know that you can send plain text, pictures, HTML, and XML in any human language. Through request metadata or different URLs, you can choose between different representations for the same resource. For example, you might send a webpage to browsers and JSON to applications.

The HTTP response should specify the content type of the body. This is done in the header, in the Content-Type field; for instance:

Content/Type: application/json

HTTP Client Libraries

To experiment with the different request methods, you need a client which allows you to decide which method to use. Unfortunately, HTML forms do not fit the bill, as they only allow you to make GET and POST requests. In real life, APIs are accessed programatically, through a separate client application or through JavaScript in the browser.

This is the reason why, in addition to the server, it is essential to have good HTTP client capabilities available in your progamming language of choice.

A very popular choice of HTTP client library is, again, cURL. You’re already been familiarized with the cURL command line over the course of this tutorial. cURL includes both a standalone command line program, and a library that can be used from many programming languages. In particular, cURL is very often the HTTP client solution of choice with PHP. Other languages, such as Python, offer more native HTTP client libraries.

Setting up the Example Application


TBC



Conclusion

It’s important to remember that HTTP was conceived to communicate between systems which share nothing but an understanding of the protocol. In general, the less assumptions beyond HTTP you make, the better: this allows the widest range of programs and devices to access your API.

my thanks to:
http://net.tutsplus.com/tutorials/other/a-beginners-introduction-to-http-and-rest/

JavaScript Module Pattern: In-Depth

0

Category :

The module pattern is a common JavaScript coding pattern. It's generally well understood, but there are a number of advanced uses that have not gotten a lot of attention.

The Basics

We'll start out with a simple overview of the module pattern

Anonymous Closures

This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We'll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.

(function () { 
    // ... all vars and functions are in this scope only 
    // still maintains access to all globals 
}());

Notice the () around the anonymous function. This is required by the language, since statements that begin with the token function are always considered to be function declarations. Including () creates a function expression instead.

Global Import

JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it's used in an assignment, the global is created if it doesn't already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it's not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals.

(function ($, YAHOO) { 
    // now have access to globals jQuery (as $) and YAHOO in this code 
}(jQuery, YAHOO));

Module Export

Sometimes you don't just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function's return value. Doing so will complete the basic module pattern, so here's a complete example:

var MODULE = (function () { 
    var my = {}, 
        privateVariable = 1; 
     
    function privateMethod() { 
        // ... 
    } 
     
    my.moduleProperty = 1; 
    my.moduleMethod = function () { 
        // ... 
    }; 
     
    return my; 
}());

Notice that we've declared a global module named MODULE, with two public properties: a method named MODULE.moduleMethod and a variable named MODULE.moduleProperty. In addition, it maintains private internal state using the closure of the anonymous function.

Advanced Patterns

While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named MODULE.

Augmentation

One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to augment modules. First, we import the module, then we add properties, then we export it. Here's an example, augmenting our MODULE from above:

var MODULE = (function (my) { 
    my.anotherMethod = function () { 
        // added method... 
    }; 
 
    return my; 
}(MODULE));

After this code has run, our module will have gained a new public method named MODULE.anotherMethod. This augmentation file will also maintain its own private internal state and imports.

Loose Augmentation

While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn't always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with loose augmentation. Each file should have the following structure:

var MODULE = (function (my) { 
    // add capabilities... 
     
    return my; 
}(MODULE || {}));

In this pattern, the var statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like LABjs and load all of your module files in parallel, without needing to block.

Tight Augmentation

While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). Tight augmentation implies a set loading order, but allows overrides. Here is a simple example (augmenting our original MODULE):

var MODULE = (function (my) { 
    var old_moduleMethod = my.moduleMethod; 
     
    my.moduleMethod = function () { 
        // method override, has access to old through old_moduleMethod... 
    }; 
     
    return my; 
}(MODULE));

Here we've overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

Cloning and Inheritance


var MODULE_TWO = (function (old) { 
    var my = {}, 
        key; 
     
    for (key in old) { 
        if (old.hasOwnProperty(key)) { 
            my[key] = old[key]; 
        } 
    } 
     
    var super_moduleMethod = old.moduleMethod; 
    my.moduleMethod = function () { 
        // override method on the clone, access to super through super_moduleMethod 
    }; 
     
    return my; 
}(MODULE));

This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility. As I've written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval. Nevertheless, I've included it for completeness.

Cross-File Private State

One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that will maintain private state across all augmentations:

var MODULE = (function (my) { 
    var _private = my._private = my._private || {}, 
        _seal = my._seal = my._seal || function () { 
            delete my._private; 
            delete my._seal; 
            delete my._unseal; 
        }, 
        _unseal = my._unseal = my._unseal || function () { 
            my._private = _private; 
            my._seal = _seal; 
            my._unseal = _unseal; 
        }; 
     
    // permanent access to _private, _seal, and _unseal 
     
    return my; 
}(MODULE || {}));

Any file can set properties on their local variable _private, and it will be immediately available to the others. Once this module has loaded completely, the application should call MODULE._seal(), which will prevent external access to the internal _private. If this module were to be augmented again, further in the application's lifetime, one of the internal methods, in any file, can call _unseal() before loading the new file, and call _seal() again after it has been executed.

Sub-modules

Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:

MODULE.sub = (function () { 
    var my = {}; 
    // ... 
     
    return my; 
}());

Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.

Conclusions

Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I'd combine loose augmentation, private state, and sub-modules.

I haven't touched on performance here at all, but I'd like to put in one quick note: The module pattern is good for performance. It minifies really well, which makes downloading the code faster. Using loose augmentation allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.

To close, here's an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I've left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.

var UTIL = (function (parent, $) { 
    var my = parent.ajax = parent.ajax || {}; 
     
    my.get = function (url, params, callback) { 
        // ok, so I'm cheating a bit :) 
        return $.getJSON(url, params, callback); 
    }; 
     
    // etc... 
     
    return parent; 
}(UTIL || {}, jQuery));

my thanks to:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Javascript Closures

0

Category :

Douglas Crockford’s five part series on Javascript

Crockford shows a much nicer object creation strategy based on closures, which looks something like this:

var animalsApp = (function(){

    var new_animal = function(name) {
        var animal = {};

        animal.sayHello = function() {
            return "Hello, my name is " + name;
        }
        return animal;
    }

    var new_dog = function(name) {
        var dog = new_animal(name);

        dog.bark = function() {
            return "woof";
        }
        return dog;
    }

    var new_cat = function(name) {
        var cat = new_animal(name);

        cat.meow = function() {
            return "eeooowww";
        }
        return cat;
    }

    return {
        main: function(){
            var dog = new_dog("rover");

            console.log(dog.sayHello());
            console.log(dog.bark());

            var cat = new_cat("tom");

            console.log(cat.sayHello());
            console.log(cat.meow());
        }
    };
}());

animalsApp.main();

Using this technique we can create properly encapsulated objects. In the example above, our animalsApp only exposes a single function, main, new_animal, new_dog and new_cat are all private. The class definitions are very clear, any variables or functions defined in the constructor body are private and we only expose members that we explicitly attach to the object (dog.bark = function(){}).


my thanks to:
http://mikehadlow.blogspot.com/2010/12/javascript-defining-classes-with.html

Javascript Functions

0

Category :

Functions in JavaScript let you define code that is called on demand, instead of immediately. There are several ways to define a function:

Function Declaration

standard function statement
  • must always have an Identifier(function name).
  • parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated before any other expressions contained in a scope.

function getarea(w,h){
 //standard function
 return w * h;
}

getarea(3,5) //calls function

Function Literal or Expression

an anonymous function assigned to a variable
var getarea = function(w,h){
 return w * h;
}

getarea(3,5) //calls function

Function Expression may omit Identifier.
Named Function Expressions may only access its Identifier in the scope of its newly-defined function
Named Function Expressions make for a much more pleasant debugging experience.

Function Constructor

creates a function on the fly, which is slower and generally discouraged
//syntax: new Function(argument1, argument2, ..., argumentY, functionbody) 
//all parameters must be a string

var getarea=new Function("w", "h", "var area=w*h; return area")
getarea(3,5) //calls function



What's the difference between declaration and expression?

The 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise! 

test1(); //alerts 'function' because test2 is a function.

ECMAScript differentiates between two based on a context. If a function foo(){} is part of, say, assignment expression, it is considered a function expression. If, on the other hand, function foo(){} is contained in a function body or in a (top level of) program itself — it is parsed as a function declaration.

// declaration, since it's part of a Program
function foo(){};

// expression, since it's part of an AssignmentExpression
var bar = function foo(){};

// expression, since it's part of a NewExpression
new function bar(){};

(function(){
  function bar(){} // declaration, since it's part of a FunctionBody
})();

A somewhat less obvious example of function expression is the one where function is wrapped with parenthesis — (function foo(){}). The reason it is an expression is again due to a context: "(" and ")" constitute a grouping operator and grouping operator can only contain an expression

function foo(){} // function declaration
(function foo(){}); // function expression: due to grouping operator
  
try {
  // grouping operator can only contain expression, 
  //not a statement (which `var` is)
  (var x = 5); 
} catch(err) {
  // SyntaxError
}

Immediately-Invoked Function Expression (IIFE)

The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

// Either of the following two patterns can be used to immediately invoke
// a function expression, thus creating an anonymous closure with privacy.

(function(){ /* code */ })(); // I've been using this one
(function(){ /* code */ }()); // Crockford recommends this one

// Because the point of the parens or coercing operators is to disambiguate
// between function expressions and function declarations, they can be
// omitted when the parser already expects an expression (but please see the
// "important note" below).


In cases where the extra “disambiguation” parens surrounding the function expression are unnecessary (because the parser already expects an expression), it’s still a good idea to use them when making an assignment, as a matter of convention. Such parens typically indicate that the function expression will be immediately invoked, and the variable will contain the result of the function, not the function itself.

Properties

arguments

A local variable that points to the "arguments" object, which contains all of the arguments passed into the function. Use "arguments.length" to determine the number of arguments entered. You can use this property to define functions that accept varying number of parameters.

caller

References the function in which the current function is called inside of. If the current function is called at the top level, caller returns null. You can use this property to check the context in which a function is being called.

function myresidence(){
 calltest()
}

// alerts function myresidence(), 
// the function in which calltest() was called inside
myresidence() 

prototype

Lets you add custom properties and methods to a function's prototype object, which instantly adds them to all instances of the function initialized using the new operator (also called a constructor function). In the below, I'm adding a getprice() method to the constructor function Car() that is reflected on all instances of new Car():

function Car(baseprice, years_old){
 this.baseprice=baseprice
 this.history=years_old
}

//add method getprice() to all instances of Car (called using new Car())
Car.prototype.getprice=function(){
 this.price=this.baseprice - (this.history * 1000)
 alert(this.price)
}

var mytoyota=new Car(20000, 10)
mytoyota.getprice() //alerts 10,000

var myford=new Car(18000, 5)
myford.getprice() //alerts 13,000

You can also use the prototype object to extend prebuilt JavaScript objects that are initialized using the new operator with custom methods, such as with Date(), Array(), or String(). Lets extend the default String object with a backwards() method that takes a string and returns it backwards (ie: "george" becomes "egroeg"):

String.prototype.backwards=function(){
 var strlen=this.length, reversestr=''
 //loop through each char within string backwards
 for (var i=strlen-1; i>-1; i--) 
  reversestr+=this.charAt(i)
 return reversestr
}

document.write('george'.backwards()) //writes out "egroeg"

Methods

funcA.apply(funcB, [argument1, argument2, argumentN])

Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. Identical to call() below, except any arguments passed into funcA should be wrapped in an array.

funcA.call(funcB, argument1, argument2, argumentN)

Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. The two methods apply() and call() are useful when you wish an object to "borrow" a method from another object and use it within its own context.

The following illustrates this:
function borrowme(name){
 this.bonus=(this.salary * 0.15) + (this.seniority * 500)
 alert(name + ", your bonus for this year is: " + this.bonus)
}

function employee(seniority, salary){
 this.seniority=seniority
 this.salary=salary
}

var employee1=new employee(10, 30000) 
//returns "Sarah, your bonus for this year is: 9500"
borrowme.call(employee1, "Sarah") 

Here the custom object "employee" uses the function "borrowme()" to manipulate a few numbers stored within it. Normally the keyword "this" in borrowme() references just that- the function itself. However, when it''s invoked using call(), the context of "this" changes so it references the object passed into the first parameter of call(), or in this case, "employee1".

apply() and call() are important tools in implementing inheritance in JavaScript.

toString()

Returns a string that represents the source code (raw text) of the function. A useful method in debugging, by looking at the source code of a function.

my thanks to:
http://www.javascriptkit.com/jsref/function.shtml
http://kangax.github.com/nfe/
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Responsive Web Design (using Media Queries)

0

Category :

CSS frameworks began winning fans by handling a lot of the grunt work for users, while offering familiar class names, structures and a set-width layout. When you knew the precise layout width, it was much easier to calculate columns and gutters.

With most displays/screens within such a limited range, it's easy to understand why both Blueprint and 960.gs (not to mention the many frameworks based on them) settled on a fixed 960 pixel-wide grid.

Fast forward to 2011, and there has never been more variation in the display ecosystem. Today, almost 30% of displays are larger than 1280 pixels—and 8% of these displays are wider than 1680 pixels. On the other hand, 960 pixels is often too wide to be truly useful on a slew of smartphones and smaller tablet devices.

Unfortunately, old-school fluid (or liquid) layouts aren't the answer. What single layout could work at 600 pixels and 1920 pixels? What we need are layouts that respond to the viewports they find themselves in.

Okay, but where do you start?

Most of these responsive layouts use CSS media queries. Media queries let us set simple tests that determine which parts of our CSS are rendered (and which aren't). For instance, you might say "if this is a monochrome display, use 'stylesheet X'".

Here's the syntax:


This line will attach the "small.css" stylesheet to our page, but only to devices with browser screens that are smaller than 1024 pixels. The moment the user resizes their browser window to a width larger than 1023px, the "small.css" is removed from the document.

CSSGrid.net

CSSGrid goes a little further than Less Framework by building in a complete 12-column layout framework.

Andy's approach works like this:

Wide screen: On large displays the layout scales fluidly up to 1139 pixels. At higher screen widths, the layout locks at 1140 pixels and centers your content.
Medium screen: On smaller desktop displays, the layout scales down fluidly until it reaches 768 pixels.
Smaller screen: On any device less than 768 pixels-wide (most often, but not exclusively, phones and smaller tablets), the layout automatically breaks down to a stacked single-column layout.
Demo........

We can let people make better use of their large displays without the risk of our content being strung out on super-wide monitors. This issue was always the killer blow to traditional fluid layouts.

On medium-sized desktops, I believe we have a much better experience than static 960-pixel grids. Sure, they can use almost all of their 1280-pixel display if that's what they want to do.

However, it's not uncommon for users to run launch bars, Twitter clients, or instant message apps on the right side of the screen. I know on my laptop, I'm unable to read any 960-pixel layout without it overlapping my Twitter client.

Allowing users to tailor your layouts to whatever space they have available helps both them and you.

There's not much argument that mobile users are becoming more widespread every day and Andy's CSSGrid provides an elegant solution out of the box. Content will stack vertically on any device less than 768 pixels wide. You write it once, and no device detection is required.

my thanks to:
http://www.sitepoint.com/newsletter/viewissue.php?id=5&issue=79

CSS Selectors you Must Memorize

0

Category :

1. X Y

li a {
  text-decoration: none;
}
Target the anchors which are within an unordered list? This is specifically when you’d use a descendant selector.

2. X:visited and X:link

a:link { color: red; }
a:visted { color: purple; }
We use the :link pseudo-class to target all anchors tags which have yet to be clicked on.

3. X + Y

ul + p {
   color: red;
}
This is referred to as an adjacent selector. It will select only the element that is immediately preceeded by the former element. In this case, only the first paragraph after each ul will have red text.

4. X > Y    (direct children)

div#container > ul {
  border: 1px solid black;
}

A selector of #container > ul will only target the uls which are direct children of the div with an id of container. It will not target, for instance, the ul that is a child of the first li.
For this reason, there are performance benefits in using the child combinator. In fact, it’s recommended particularly when working with JavaScript-based CSS selector engines.

5. X[title]

a[title] {
   color: green;
}
Referred to as an attributes selector, in our example above, this will only select the anchor tags that have a title attribute.

6. X[href="foo"]

a[href="http://net.tutsplus.com"] {
  color: #1f6053; /* nettuts green */
}
The snippet above will style all anchor tags which link to http://net.tutsplus.com; they’ll receive a branded green color. All other anchor tags will remain unaffected.

7. X[href*="nettuts"]

a[href*="tuts"] {
  color: #1f6053; /* nettuts green */
}
There we go; that’s what we need. The star designates that the proceeding value must appear somewhere in the attribute’s value. That way, this covers nettuts.com, net.tutsplus.com, and even tutsplus.com.

8. X[href^="http"]

a[href^="http"] {
   background: url(path/to/external/icon.png) no-repeat;
   padding-left: 10px;
}
If we want to target all anchor tags that have a href which begins with http, we could use a selector similar to the snippet shown above. This is a cinch with the carat symbol. It’s most commonly used in regular expressions to designate the beginning of a string.

9. X[href$=".jpg"]

a[href$=".jpg"] {
   color: red;
}
Again, we use a regular expressions symbol, $, to refer to the end of a string. In this case, we’re searching for all anchors which link to an image — or at least a url that ends with .jpg. Keep in mind that this certainly won’t work for gifs and pngs.

10. X:checked

input[type=radio]:checked {
   border: 1px solid black;
}
This pseudo class will only target a user interface element that has been checked - like a radio button, or checkbox. It's as simple as that.

11. X:after

The before and after pseudo elements kick butt. Every day, it seems, people are finding new and creative ways to use them effectively. They simply generate content around the selected element.
Many were first introduced to these classes when they encountered the clear-fix hack.

.clearfix:after {
    content: "";
    display: block;
    clear: both;
    visibility: hidden;
    font-size: 0;
    height: 0;
 }

.clearfix {
   *display: inline-block;
   _height: 1%;
}

This hack uses the :after pseudo element to append a space after the element, and then clear it. It's an excellent trick to have in your tool bag, particularly in the cases when the overflow: hidden; method isn't possible.

12. X:hover

div:hover {
  background: #e3e3e3;
}
Oh come on. You know this one. The official term for this is user action pseudo class. It sounds confusing, but it really isn't. Want to apply specific styling when a user hovers over an element? This will get the job done!

13. X:not(selector)

div:not(#container) {
   color: blue;
}
The negation pseudo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.

14. X::pseudoElement

p::first-line {
   font-weight: bold;
   font-size: 1.2em;
}
We can use pseudo elements (designated by ::) to style fragments of an element, such as the first line, or the first letter. Keep in mind that these must be applied to block level elements in order to take effect.

15. X:nth-child(n)

li:nth-child(3) {
   color: red;
}
Remember the days when we had no way to target specific elements in a stack? The nth-child pseudo class solves that!
Please note that nth-child accepts an integer as a parameter, however, this is not zero-based. If you wish to target the second list item, use li:nth-child(2).
We can even use this to select a variable set of children. For example, we could do li:nth-child(4n) to select every fourth list item

16. X:first-child

ul li:first-child {
   border-top: none;
}
This structural pseudo class allows us to target only the first child of the element's parent. You'll often use this to remove borders from the first and last list items.
For example, let's say you have a list of rows, and each one has a border-top and a border-bottom. Well, with that arrangement, the first and last item in that set will look a bit odd.
Many designers apply classes of first and last to compensate for this. Instead, you can use these pseudo classes.

17. X:first-of-type

The first-of-type pseudo class allows you to select the first siblings of its type.

A Test

To better understand this, let's have a test. Copy the following mark-up into your code editor:

<div>
   <p> My paragraph here. </p>
   <ul>
      <li> List Item 1 </li>
      <li> List Item 2 </li>
   </ul>

   <ul>
      <li> List Item 3 </li>
      <li> List Item 4 </li>
   </ul>
</div>

Now, without reading further, try to figure out how to target only "List Item 2". When you've figured it out (or given up), read on.

Solution 1

There are a variety of ways to solve this test. We'll review a handful of them. Let's begin by using first-of-type.

ul:first-of-type > li:nth-child(2) {
   font-weight: bold;
}
This snippet essentially says, "find the first unordered list on the page, then find only the immediate children, which are list items. Next, filter that down to only the second list item in that set.

Solution 2

Another option is to use the adjacent selector.

p + ul li:last-child {
   font-weight: bold;
}
In this scenario, we find the ul that immediately proceeds the p tag, and then find the very last child of the element.

Solution 3

We can be as obnoxious or as playful as we want with these selectors.

ul:first-of-type li:nth-last-child(1) {
   font-weight: bold;
}
This time, we grab the first ul on the page, and then find the very first list item, but starting from the bottom!
:)

 my thanks to:
http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+nettuts+%28Nettuts%2B%29

Common JavaScript Design Pattern - jQuery.doc.ready

0

Category :

Let me show you an overview, and then look at how it comes together:

function MyScript(){}
(function()
{
  var THIS = this;
  function defined(x)
  {
    return typeof x != 'undefined';
  }
  this.ready = false;
  this.init = function(
  {
    this.ready = true;
  };
  this.doSomething = function()
  {
  };   
  var options = {
      x : 123,
      y : 'abc'
      };
  this.define = function(key, value)
  {
    if(defined(options[key]))
    {
      options[key] = value;
    }
  };
}).apply(MyScript);

As you can see from that sample code, the overall structure is a function literal:
(function()
{
  ...
})();

A function literal is essentially a self-executing scope, equivalent to defining a named function and then calling it immediately:

function doSomething()
{
  ...
}

doSomething();

I originally started using function literals for the sake of encapsulation—any script in any format can be wrapped in that enclosure, and it effectively “seals” it into a private scope, preventing it from conflicting with other scripts in the same scope, or with data in the global scope. The bracket-pair at the very end is what executes the scope, calling it just like any other function.

But if, instead of just calling it globally, the scope is executed using Function.apply, it can be made to execute in a specific, named scope which can then be referenced externally.

So by combining those two together—the creation of a named function, then the execution of a function literal into the scope of the named function—we end up with a single-use object that can form the basis of any script, while simulating the kind of inheritance that’s found in an object-oriented class.

The Beauty Within

By wrapping it up in this way we have a construct that can be associated with any named scope. We can create multiple such constructs, and associate them all with the same scope, and then all of them will share their public data with each other.

But at the same time as sharing public data, each can define its own private data too. Here for example, at the very top of the script:

var THIS = this; 

We’ve created a private variable called THIS which points to the function scope, and can be used within private functions to refer to it

Private functions can be used to provide internal utilities:
function defined(x)
{
  return typeof x != 'undefined';
}

Then we can create public methods and properties, accessible to other instances, and to the outside:
this.ready = false;
this.init = function()
{
  this.ready = true;
};
this.doSomething = function()
{
};

We can also create privileged values—which are private, but publicly definable, in this case via the public define method; its arguments could be further validated according to the needs of the data:

var options = {
  x : 123,
  y : 'abc'
  };
this.define = function(key, value)
{
  if(defined(options[key]))
  {
    options[key] = value;
  }
};

THIS or That?

The enclosing scope of any function can be referred to as this, so when we define a named or anonymous enclosure, this refers to that enclosure at the top level; and it continues to refer to that enclosure from within its public methods.

But within private functions, this refers to the immediate enclosing scope (the private function), not the top-level enclosing scope. So if we want to be able to refer to the top-level scope, we have to create a variable which refers to it from anywhere. That’s the purpose of "THIS":

function MyScript(){}
(function()
{
   var THIS = this;  
   function defined(x)
   {
      alert(this);      //points to defined()
      alert(THIS);      //points to MyScript()
   }
}).apply(MyScript);

Wrapped Up!

All of these features are what makes the construct so useful to me. And it’s all wrapped up in a neat, self-executing singleton —a single-use object that’s easy to refer-to and integrate, and straightforward to use!


my thanks to:
http://blogs.sitepoint.com/2010/11/30/my-favorite-javascript-design-pattern/
http://blogs.sitepoint.com/2010/12/08/the-anatomy-of-a-javascript-design-pattern/