Javascript 이벤트 전파(bubbling, capturing)와 중단

어떤 element에서 발생한 이벤트는 부모 혹은 자식에게 전파되게 되는데, 이때 전파되는 방향에 따라 버블링(bubbling), 캡쳐링(capturing)이라고 부른다.

먼저 javascript addEventListener() 함수를 살펴보자.

document.addEventListener(event, function, useCapture)
  • event: 이벤트의 이름을 명시한다. (click, mouseover 등)
  • function: 이벤트가 발생했을 때 실행할 함수를 명시한다.
  • useCapture: Optional. capturing에서 해당 이벤트가 실행될 것인지 여부를 명시한다. (true면 capturing, false(default)면 bubbling으로 실행)

1. Bubbling

Bubbling은 이벤트가 발생한 element부터 조상들에게 순차적으로 이벤트가 전파되는 방식이다.

2. Capturing

Capturing은 이벤트가 발생한 element부터 자식들에게 순차적으로 이벤트가 전파되는 방식이다.

이러한 이벤트 전파를 막을 수 있는 방법은 총 4가지가 있다:

event.preventDefault()

현재 이벤트의 default 동작을 중단한다. 예를 들면 a 태그의 경우 클릭하면 명시된 href로 이동하는 것이 default 동작이다.

event.stopPropagation()

현재 이벤트가 bubbling 혹은 capturing 되는 것을 막는다.

event.stopImmediatePropagation()

bubbling 혹은 capturing 뿐만 아니라, 해당 개체에 걸린 현재 event를 제외한, 다른 event들의 동작까지 막는다.

return false

jQuery event handler의 경우는, stopPropagation()stopImmediatePropagation()을 모두 수행한 것과 같고 그 외의 handler 경우(non-jQuery)에서는, preventDefault()를 수행한 것과 같다.

Javascript Tutorial 22 Throw and Try to Catch

  • The try statement lets you test a block of code for errors.
  • The catch statement lets you handle the error.
  • The throw statement lets you create custom errors.
  • The finally statement lets you execute code, after try and catch, regardless of the result.

The throw statement allows you to create a custom error.

Technically you can throw an exception (throw an error).

The exception can be a JavaScript String, a Number, a Boolean or an Object:

throw "Too big";    // throw a text
throw 500;          // throw a number
try { 
    if(x == "") throw "empty";
    if(isNaN(x)) throw "not a number";
    x = Number(x);
    if(x < 5) throw "too low";
    if(x > 10) throw "too high";
} catch(err) {
    message.innerHTML = "Input is " + err;
} finally {
    document.getElementById("demo").value = "";
}

Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:

<input id="demo" type="number" min="5" max="10" step="1">

JavaScript has a built in error object that provides error information when an error occurs.

The error object provides two useful properties: name and message.

Mozilla and Microsoft defines some non-standard error object properties:

  • fileName (Mozilla)
  • lineNumber (Mozilla)
  • columnNumber (Mozilla)
  • stack (Mozilla)
  • description (Microsoft)
  • number (Microsoft)

Do not use these properties in public web sites. They will not work in all browsers.

Error Name Values

  • EvalError: An error has occurred in the eval() function
    • Newer versions of JavaScript does not throw any EvalError. Use SyntaxError instead.
  • RangeError: If you use a number that is outside the range of legal values.
  • ReferenceError: If you use (reference) a variable that has not been declared.
  • SyntaxError: If you try to evaluate code with a syntax error.
  • TypeError: If you use a value that is outside the range of expected types.
  • URIError: If you use illegal characters in a URI function encodeURI().

Javascript Tutorial 21 RegExp Object

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

/pattern/modifiers;

var patt = /w3schools/i;

Regular Expression Modifiers

Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching

Regular Expression Patterns

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with
Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n

In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or false, depending on the result.

var patt = /e/;
patt.test("The best things in life are free!"); // Since there is an "e" in the string, it returns true

The exec() method is a RegExp expression method. It searches a string for a specified pattern, and returns the found text.

/e/.exec("The best things in life are free!");  // Since there is an "e" in the string, it returns e