Skip to main content

Ivan Teoh

Something personal yet public

Javascript: 101 Week 5 Track 1

On this week, we continue watching 'An Incovenient API - The Theory of the DOM' part 2 as below by Douglas Crockford

Reflection

  • Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked? Trickling is an event capturing pattern which provides compatibility with the Netscape 4 model. Avoid it. On the other hand, bubbling means that the event is given to the target, and then its parent, and then its parent, and so on until the event is cancelled. Bubble is very useful specially we have a very large set of objects. Supposedly we have 100 draggable objects. We could attach 100 sets of event handlers to those objects. Or we could attach one set of event handlers to the container of the 100 objects.

  • Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the 'submit' button? How would you achieve this? Cancel bubbling is to keep the parent nodes from seeing the event.

    173-reflection1.js (Source)

    e.cancelBubble = true;
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    

    Cancel bubbling is not enough. After all the bubbling is finished, the browser will then do what it's normally does. An event handler as below can prevent a browser action associated with the event (such as submitting a form).

    173-reflection2.js (Source)

    e.returnValue = false; // from Netscape
    if (e.preventDefault) { // from w3c
        e.preventDefault();
    }
    return false; // event handler return false
    

Homework

Since track 1 is the same as track 2 in week 5, the answer for the homework will be in track 2 post.

Comments

Comments powered by Disqus