JavaScript Event

ITWeb/개발일반 2008. 2. 20. 17:41


 
-The browser has an event-driven, single-threaded, asynchronous programming model.
-Events are targeted to particular nodes.
-Events cause the invocation of event handler functions.
-Events are normally used in combination with functions, and the function will not be executed before the event occurs!

 
Attribute
The event occurs when...
FF
N
IE
onabort
Loading of an image is interrupted
1
3
4
onblur
An element loses focus
1
2
3
onchange
The user changes the content of a field
1
2
3
onclick
Mouse clicks an object
1
2
3
ondblclick
Mouse double-clicks an object
1
4
4
onerror
An error occurs when loading a document or an image
1
3
4
Onfocus
An element gets focus
1
2
3
onkeydown
A keyboard key is pressed
1
4
3
onkeypress
A keyboard key is pressed or held down
1
4
3
onkeyup
A keyboard key is released
1
4
3
onload
A page or an image is finished loading
1
2
3
onmousedown
A mouse button is pressed
1
4
4
onmousemove
The mouse is moved
1
6
3
onmouseout
The mouse is moved off an element
1
4
4
onmouseover
The mouse is moved over an element
1
2
3
onmouseup
A mouse button is released
1
4
4
onreset
The reset button is clicked
1
3
4
onresize
A window or frame is resized
1
4
4
onselect
Text is selected
1
2
3
onsubmit
The submit button is clicked
1
2
3
onunload
The user exits the page
1
2
3

 
Event parameter
-function getCBEvent (oNsEvent, PARAM1…) {
// window.event : ff 에서 undefined
var oEvent = oNsEvent || window.event;
var oTarget = oEvent.target || oEvent.srcElement;
}
onclick=getCBEvent(event, param1,..,parmaN);
-Microsoft does not send an event parameter, use the global event object instead

Event listener.
Classic
§node["on" + type] = f;
Microsoft
§node.attachEvent("on" + type, f);
W3C
§node.addEventListener(type, f, false);
Example :
§if ( DOMObject.addEventListener ) {
§ DOMObject.addEventListener("click", getMsg, false);
§} else if (DOMObject.attachEvent ) {
§ DOMObject.attachEvent("onclick", getMsg);
§} else if (DOMObject.onclick ) {
§ DOMObject.onclick = getMsg; // or
§ DOMObject["onclick“] = getMsg;
§}

 
Event bubbling
-Event bubbling is that the event is delivered in  elements, and so on until the event is canceled.
Cancel bubbling
-function cancelBubbling ( oEvent ) {
if ( oEvent.stopPropagation ) {
oEvent.stopPropagation(); // FF
} else {
oEvent.cacnelBubble = true; // IE
}
}



:

JavaScript DOM

ITWeb/개발일반 2008. 2. 20. 17:34

 
Node
-Retrieving nodes
§document.getElementById(id)
§document.getElementsByName(name)
§node.getElementsByTagName(tagName)

 
Node
Document tree structure

사용자 삽입 이미지


 
Node
-child, sibling, parent

사용자 삽입 이미지



 
Walk the DOM
-Using recursion, follow the firstChild node, and then the nextSibling nodes.
§function walkTheDOM(node, func) {
§ func(node);
§ node = node.firstChild;
§ while (node) {
§ walkTheDOM(node, func);
§ node = node.nextSibling;
§ }
§}

 
Style
-node.className
-node.style.stylename
-node.currentStyle.stylename Only IE
-document.defaultView(). getComputedStyle(node, ""). getPropertyValue(stylename);
§var oDiv = document.getElementById("div1");
§var nHeight = document.defaultView.getComputedStyle(oDiv, null).getPropertyValue("height");

 
Style names
CSS
background-color
border-radius
font-size
list-style-type
word-spacing
z-index
JavaScript
backgroundColor
borderRadius
fontSize
listStyleType
wordSpacing
zIndex

 
Making elements
-document.createElement(tagName)
§var hr = document.createElement("hr");
§document.body.appendChild(hr);
-document.createTextNode(text)
§var txt = document.createTextNode("Hello!");
§document.body.appendChild(txt);
-node.cloneNode(deep);
§cloneNode(true) clones the whole subtree rooted at the node
§cloneNode(false) only the node itself (and any attributes if it is an element) is cloned
curr_node = root.firstChild;
var new_node = curr_node.cloneNode(true);
root.appendChild(new_node);

 
Linking elements
-node.appendChild(new)
-node.insertBefore(new, sibling)
-node.replaceChild(new, old)
-old.parentNode.replaceChild(new, old)
Removing elements
-node.removeChild(old)
-old.parentNode.removeChild(old)

 
innerHTML
-The W3C standard does not provide access to the HTML parser.
-All A browsers implement Microsoft's innerHTML property.
:

javascript object, class & inheritance, sigletons

ITWeb/개발일반 2008. 2. 20. 17:08

 
Class & Inheritance

사용자 삽입 이미지



















 
Class & Inheritance
-Prototypal Inheritance
var oldObject = {
    firstMethod: function () { alert("first"); },
    secondMethod: function () { alert("second"); }
};
var newObject = new Object(oldObject);
newObject.thirdMethod = function () { alert("third"); };
var myDoppelganger = new Object(newObject);
myDoppelganger.firstMethod(); // or
myDoppelganer[“firstMethod”]();
var obj1 = function () {
this.title = "obj1";
}
var obj2 = function () {}
obj2.prototype = new obj1;
var obj2Class = new obj2();
alert(obj2Class.title);
obj1 = {
title:"obj1_"
}
obj2 = new Object(obj1);
alert(obj2.title);

 
-Method apply (Member variable)
§Function.apply(thisArg[, argArray])
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
 
function RentalCar(carNo, make, model, year) {
  this.carNo = carNo;
  Car.apply(this, new Array(make, model, year));
}
 
myCar = new RentalCar(2134,"Ford","Mustang",1998);
document.write("Your car is a " + myCar.year + " " + myCar.make + " " + myCar.model + ".");

 
-Method apply (Member function)
§function TopClass (name, value) {
§ this.name = name;
§ this.value = value;
§ this.getAlertData = function () {
§ alert(this.name);
§ alert(this.value);
§ }
§}
§function SubClass (name, value, dept) {
§ this.dept = dept;
§ TopClass.apply(this, arguments);
§ this.getView = function () {
§ this.getAlertData();
§ }
§}
§//SubClass.prototype = new TopClass();
§var objSubClass = new SubClass("상위클래스","super","community");
§objSubClass.getView();

 
-Method call
§Function.call(thisArg[, arg1[, arg2[, ...]]])
function car(make, model, year) {
    this.make = make, this.model = model, this.year = year;
}
 
function hireCar(carNo, make, model, year) {
    this.carNo = carNo, car.call(this, make, model, year);
}

 
-Prototype
Profiler = function () {..}
Profiler.prototype.name = function () {..}
-Namespace
YAHOO = {};
-new operator
function object(o) {
function F() {};
F.prototype = o;
return new F();
}
classA = new Profiler(); or classA = object(Profiler);

 
-Encapsulate (Parasitic)
YAHOO = {};
YAHOO.Trivia = function () {
    var privateVar = "showPoser";
    function privateNextPoser() {
        alert("getNextPoser");
    }
    return {
        getNextPoser: function (cat, diff) {
            privateNextPoser();
        },
        showPoser: function () {
            alert(privateVar);
        }
    };
} ();
function getFunc() {
var oObj = YAHOO.Trivia;
oObj.getNextPoser();
}
YAHOO = {};
YAHOO.Trivia = function () {
    var privateVar = "showPoser";
    function privateNextPoser() {
        alert("getNextPoser");
    }
    return {
        getNextPoser: function (cat, diff) {
            privateNextPoser();
        },
        showPoser: function () {
            alert(privateVar);
        }
    };
};
function getFunc() {
var oObj = new YAHOO.Trivia();
oObj.getNextPoser();
}

 
-Singletons
var singleton = function () {
    var privateVariable;
    function privateFunction(x) {
        ...privateVariable...
    }
    return {
        firstMethod: function (a, b) {
            ...privateVariable...
        },
        secondMethod: function (c) {
            ...privateFunction()...
        }
    };
}();





:

내장객체, BOM, DOM, 사용자 정의 객체

ITWeb/개발일반 2008. 2. 20. 16:47
 
자바스크립트 내장 객체
-Number
-String
-Date
-Array
-Boolean
-Math
-RegExp

 
브라우저 객체 모델(BOM) 객체
-window
§document
forms
cookie
links/anchors
images
§navigator
§location
§frames
§screen
§history

 
The Document Object Model (DOM) is an API for HTML and XML documents.
-Core DOM
§defines a standard set of objects for any structured document
-XML DOM
§defines a standard set of objects for XML documents
-HTML DOM
§defines a standard set of objects for HTML documents
 
DOM 객체
DOM Level 1,2,3
§DOM1 : 1997~1998
§DOM2 : 2000~2003
§DOM3 : 2004
Specification
 
DOM Level 1
DOM Level 1 (SE)
 
DOM Level 2 Core
DOM Level 2 HTML
DOM Level 2 Views
DOM Level 2 Style
DOM Level 2 Events
DOM Level 2 Traversal-Range
 
DOM Level 3 Requirements
DOM Level 3 Core
DOM Level 3 Events
DOM Level 3 Load and Save
DOM Level 3 Validation
DOM Level 3 XPath
DOM Level 3 Views

 
개발자가 만든 사용자 정의 객체
-JavaScript objects prototype.
§YAHOO.util.Connect = {
_msxml_progid:[],
_http_headers:{},
_has_http_headers:false,
setProgId:function(){}
}
§Profiler = function () {
var getProfilers; // private
this.getProfiler = function () {…} // public
}
§String.prototype.trim = functoin () {}
§Profiler = new Object();
Profiler.title = YAHOO;
Profiler.author = “Jerry”;


:

objects, collections, linkage, invocations, this, typeof, closure, namespace, inheritance

ITWeb/개발일반 2008. 2. 20. 16:36

Objects
-Everything else is objects
-Objects can contain data and methods
-Objects can inherit from other objects.

 
Collections
-An object is an unordered collection of name/value pairs
-Names are strings
-Values are any type, including other objects
-Good for representing records and trees
-Every object is a little database
§var FUNC = function () {
§ var objDiv = document.createElement("div");
§ this.getCollection = function ( collection ) {
§ for ( i in collection ) {
§ objDiv.innerHTML += "name : " + i + "<br>value : " + collection[i] + "<br>";
§ }
§ document.body.appendChild(objDiv);
§ }
§}
§FUNC = new FUNC();

 
Object Literals
-Object literals are wrapped in { }
-Names can be names or strings
-Values can be expressions
-: separates names and values
-, separates pairs
-Object literals can be used anywhere a value can appear

 
Linkage
-Objects can be created with a secret link to another object.
-If an attempt to access a name fails, the secret linked object will be used.
-The secret link is not used when storing. New members are only added to the primary object.
-The object(o) function makes a new empty object with a link to object o.

function object(o) {
function F() {};
F.prototype = o;
return new F();
}

 
JavaScript Invocations
-If a function is called with too many arguments, the extra arguments are ignored.
-If a function is called with too few arguments, the missing values will be undefined.
-There is no implicit type checking on the arguments.
-There are four ways to call a function:
§Function form
functionObject(arguments)
§Method form
thisObject.methodName(arguments)
thisObject["methodName"](arguments)
§Constructor form
new functionObject(arguments)
§Apply form
functionObject.apply(thisObject, [arguments])

 
JavaScript this
-this is an extra parameter. Its value depends on the calling form.
-this gives methods access to their objects.
-this is bound at invocation time.
Invocation form
this
function
the global object
method
the object
constructor
the new object

 
JavaScript typeof
type
typeof
object
'object'
function
'function'
array
'object'
number
'number'
string
'string'
boolean
'boolean'
null
'object'
undefined
'undefined'

 
Closure
-The scope that an inner function enjoys continues even after the parent functions have returned.
-This is called closure.
§function getClosure () {
§  var num = 1;
§  var getAlert = function() { num++; alert(num); }
§  num++;
§  return getAlert();
§}
§<input type="button" value="getClosure" onclick="getClosure();">

 
function fade(id) {
    var dom = document.getElementById(id),
        level = 1;
    function step () {
        var h = level.toString(16);
        dom.style.backgroundColor =
            '#FFFF' + h + h;
        if (level < 15) {
            level += 1;
            setTimeout(step, 100);
        }
    }
    setTimeout(step, 100);
}

 
JavaScript Namespace
-Every object is a separate namespace.
-Use an object to organize your variables and functions.
-The YAHOO Object.
§var YAHOO = {};
§YAHOO.url = "http://www.yahoo.com";
§YAHOO.getUrl = function () {
§ alert(this.url);
§ return this.url;
§}
§<input type="button" value="YAHOO.getUrl();" onclick="YAHOO.getUrl();">

 
Inheritance
-Linkage provides simple inheritance.
-Prototypal inheritance.
-Parasitic inheritance.
-Method apply(), call().
 


: