Tuesday, September 9, 2014

XMLHttpRequest (XHR)

XMLHttpRequest() is an object (a constructor function) that allows you to send HTTP requests from JavaScript.

AJAX stands for Asynchronous JavaScript and XML

two steps to using the XMLHttpRequest:

  • Send the request—this includes creating an XMLHttpRequest object and attaching an event listener
  • Process the response—your event listener gets notified that the response has arrived


Send the Request

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = myCallback;
xhr.open('GET', 'somefile.txt', true);
xhr.send('');

HTTP request GET, POST, HEAD
The last parameter is a boolean specifying whether the request is asynchronous (true) or not (false).

Process the Response

There is a property of the XHR object called readyState

Every time it changes, the readystatechange event fires

0—uninitialized
1—loading
2—loaded
3—interactive
4—complete (response is back)

function myCallback() {
if (xhr.readyState < 4) {
return; // not ready yet
}
if (xhr.status !== 200) {
alert('Error!'); // the HTTP status code is not OK
return;
}
// all is fine, do the work
alert(xhr.responseText);
}




Events

browser broadcasts events

Can attach a JavaScript function (called an event listener or event handler) to a specific event and the browser will execute your function as soon the event occurs

Inline HTML Attributes

<div onclick="alert('Ouch!')">click</div>

Behind the scenes a function is still created and it contains the code you specified as a value of the onclick attribute

Element Properties

Assign a function to the onclick property of a DOM node element

<div id="my-div">click</div>
<script type="text/javascript">
    var myelement = document.getElementById('my-div');
    myelement.onclick = function() {
        alert('Ouch!');
        alert('And double ouch!');
    }
</script>


Drawback that you can attach only one function to the event

DOM Event Listeners

You can have many functions listening to an event

When the event fires, all functions are executed

Example:

<p id="closer">final</p>

>>> var mypara = document.getElementById('my-div');
>>> mypara.addEventListener('click', function()
{alert('Boo!')}, false);
>>> mypara.addEventListener('click', console.log, false);

Removing Event Listeners

to remove the event listener, use removeEventListener()

If you remove a listener, you have to pass a pointer to the same function you previously attached.
So you cannot remove listeners that use anonymous functions.

>>> para.addEventListener('click', paraHandler, false);
>>> para.removeEventListener('click', paraHandler, false);


Capturing and Bubbling

third parameter in addEventListener

DOM Level 2 Events specification suggests that the events propagate in three phases

capturing
target
bubbling



Historically

  • IE implemented only bubbling
  • Netscape only capturing
  • Firefox, Opera, and Safari implemented the three phases

You can stop the propagation of the event, in your listeners, so that it stops bubbling up and never reaches the document. To do this you can call the stopPropagation() method of the event object.

You can also use event delegation.
If you have ten buttons inside a <div>, you can always attach ten event listeners, one for each button. But a smarter thing to do is to attach only one listener to the wrapping <div> and when the event happens, check which button was the target of the click.

Prevent Default Behavior

// all links
var all_links = document.getElementsByTagName('a');
for (var i = 0; i < all_links.length; i++) { // loop all links
all_links[i].addEventListener('click', // event type
function(e) { // handler
if (!confirm('Are you sure you want to follow this link?')) {
e.preventDefault();
}
}, false); // don't use capturing
}

Not all events allow you to prevent the default behavior
can check the cancellable property of the event object.

Inheritance - Prototype Chaining

Every function has a prototype property, which contains an object.
When this function is invoked using the new operator, an object is created and this object has a secret link to the prototype object
When this function is invoked using the new operator, an object is created and this object has a secret link to the prototype object


Saturday, September 6, 2014

Prototype

Prototype property of a function

Every function has a prototype property and it contains an object

>>> function foo(a, b){return a * b;}
>>> typeof foo.prototype
"object"

It's as if you added this property yourself like this:
>>> foo.prototype = {}

prototype property of a Constructor function

Let's take a look at the constructor function Gadget

function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function() {
return 'I am a ' + this.color + ' ' + this.name;
}
}

Adding methods and properties to the prototype property of the constructor function is another way to add functionality to the objects this constructor produces.

Adding properties to the prototype object

Let's add two more properties, price and rating, and a getInfo() method

Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
};

another way to achieve the above result is to overwrite the prototype completely, replacing it with an object of your choice

Gadget.prototype = {
price : 100,
rating : 3,
getInfo : function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
}
};

How JavaScript Engine looks for a property

>>> var newtoy = new Gadget('webcam', 'black');
>>> newtoy.price;
100

JavaScript engine will look through all of the properties of the object.
If the property is not found, it will search the prototype of the constructor function used to create this object.

Gadget.prototype = {
price : 100,
rating : 3,
getInfo : function() {
return 'Rating: ' + Gadget.prototype.rating + ', price: ' + Gadget.prototype.price;
}
};

>>> newtoy.rating
3

>>> newtoy.constructor
Gadget(name, color)

>>> newtoy.constructor.prototype.rating
3

Overwriting Prototype's Property with Own Property

The own property takes precedence over the prototype's

Enumerating Properties

var a = [ 1, 2, 3 ];
for ( var i in a) {
console.log(a[i]);
}

var o = {p1: 1, p2: 2};
for (var i in o) {
console.log(i + '=' + o[i]);
}

o/p:
p1=1
p2=2

Points to note

Not all properties show up in a for-in loop. The properties that do show up are called enumerable.
Prototypes that come through the prototype chain will also show up as long as they are enumerable.

Related object methods

propertyIsEnumerable()

  • can check which properties are enumerable
  • return false for all of the prototype's properties

hasOwnProperty()

  • can check if a property is an own property versus prototype's

isPrototypeOf()

Every object also gets the isPrototypeOf() method
This method tells you whether that specific object is used as a prototype of another object.

var monkey = {
hair : true,
feeds : 'bananas',
breathes : 'air'
};

function Human(name) {
this.name = name;
}
Human.prototype = monkey;

>>> var george = new Human('George');

"Is monkey george's prototype?"

>>> monkey.isPrototypeOf(george)
true

The Secret __proto__ Link

The prototype property will be consulted when you try to access a property that does not exist in the current object.

var monkey = {
feeds : 'bananas',
breathes : 'air'
};
function Human() {
}
Human.prototype = monkey;

var developer = new Human();
developer.feeds = 'pizza';
developer.hacks = 'JavaScript';

>>> developer.constructor = 'junk'
"junk"

>>> typeof developer.constructor.prototype
undefined

but the following still works

>>> developer.breathes
"air"

This shows that the secret link to the prototype still exists __proto__

>>> developer.__proto__
Object feeds=bananas breathes=air

because it does not exist in Internet Explorer, so your scripts won't be portable.

__proto__ is a property of the instances, whereas prototype is a property of the constructor functions

Augmenting Built-in Objects

Array, String, and even Object, and Function can be augmented through their prototypes.
Can, for example, add new methods to the Array prototype and in this way make them available to all arrays.

String.prototype.reverse = function() {
return Array.prototype.reverse.apply(this.split('')).join('');
}

>>> "Stoyan".reverse();
"nayotS"

Error

JavaScript provides the statements try, catch, and finally to help you deal with errors

Error objects are created by using one of these built-in constructors:

  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

All of these constructors inherit from the Error object.

An example of an error will be trying to call a function that doesn't exist

>>> iDontExist();

try {
iDontExist();
} catch (e) {
// do nothing
}

try {
iDontExist();
} catch (e) {
alert(e.name + ': ' + e.message);
} finally {
alert('Finally!');
}

You can also create error objects yourself using new Error() or any of the other error constructors

try {
var total = maybeExists();
if (total === 0) {
throw new Error('Division by zero!');
} else {
alert(50 / total);
}
} catch (e) {
alert(e.name + ': ' + e.message);
} finally {
alert('Finally!');
}

Alternatively, you don't need any constructor; you can simply throw a normal object:

throw {
name : "MyError",
message : "OMG! Something terrible has happened"
}

Math & Date

String