Event Bubbling in a Nutshell

When reading through Stack Overflow posts having to do with Javascript, I sometimes came across the term Event Bubbling and never knew what it was really.  I decided to sit down and spend some time learning about it so I wouldn’t be puzzled anymore by it.  My main learning resources were two excellent Youtube tutorial videos:  Javascript Event Capture, Propogation and Bubbling by Wes Bos and Event Bubbling by The Net Ninja.   This is an excellent article as well on the topic.  I recommend you at least watch the Youtube tutorials, but I am going to attempt to boil the subject down into a single post here.

Event Bubbling In a Nutshell:

  • Events (such as ‘click’ events, for example) are registered not only by the target element where they originate, but by all of that element’s parents all the way up to the global element (i.e. the Window/Browser).
  • An Event occurs (a ‘click’, for example) and the click event is registered (this means recorded or noted and recognized by the browser).  The registered click event then goes from the Window Object down through the child elements and is registered on each during a ‘Capture Phase’ (<html> –> <body> –> <div> –> <form> –> <button>, for example) to find the Target Element (where the click event originated from, i.e. what element was clicked).  Once the click event has registered on the Target (‘Target Phase’), it then bubbles back up the DOM Tree (‘Event Bubbling Phase’) and is registered on all parent elements up through the Window Object triggering any Event Listeners or Handlers in the process.

Why it’s important to understand: 

  • To avoid unintentional Event Handle triggering on parent elements of the target, or to intentionally incorporate handling the event on a parent element. 
  • If there are any identical Event Listeners on the parent elements of the Event Target, then their respective Event Handlers will be triggered.  A click event on element A will trigger element A’s Event Handler as well as Element A’s parents’ Event Handlers for a click event.  

For more information and examples, keep reading:

Definitions:

  • Window Object: My non-technical understanding is to just think of it as the browser or the window you have open in the browser.  It contains all of the elements on the page.
  • Event Target:  The element that the Event originated from (i.e. the element that was clicked, for example).
  • Event Capture: The process of recording events that occur starting at the top of the DOM (the Window Object) and down through the parent elements related to the Event Target.
  • Event Propagation: To propagate, literally means to spread and promote widely.  The event is ‘spread widely’ and registered throughout the DOM tree from the top (Window Object) down to the event target, and back up to the top again.
  • Event Bubbling: The process in which the Event is registered on each successive parent element of the Event Target element all the way up to the Window Object.
  • Event Target Phase: This occurs in between the Capture and Bubbling Phase during Event Propagation.  During this phase, any listeners on the Event Target for the Event and their respective functions will be triggered and invoked.

The Process:

Event Bubbling happens in the course of what’s called Event Propagation, which has three main parts:

  • The Capture Phase: The event is recorded from the top of the DOM and down to find the event target.
  • The Target Phase: The Event is registered on the Target (the element it originated from) and any Listeners or Handlers are fired.
  • The Event Bubbling Phase:  After the Capture and Event Target Phase, the event is registered on each parent element of the Event Target, in order, up through the DOM Tree to the Window Object.

Important Note: Branch paths in the DOM for Events during Event Bubbling are static:  If the DOM tree is modified after the Event Listeners have been assigned, the modified DOM tree or added elements will not be used or included in the Event Bubbling process.

For example, if the handling of the Event involves creating/appending/inserting an additional parent element of the Event Target, then the inserted parent element will not register the Event as it bubbles up the DOM tree on future click events originating from the Event Target.  The Event will bubble only up through parent elements present in the DOM Tree when the Event Listener for that target was assigned (for instance, at the loading up of the page).

Additionally, an Event Listener that is assigned to a class of elements will not be applied to any elements of that class that are later added to the DOM Tree.

Scenarios Where Understanding Event Bubbling Can Help:

Example (consider the following HTML which contains a list of items with buttons that give the user the option to remove the item from the list, or add an item to the list):

<div>
  <ul id='theList'>
     <li id='item_copy'>List Item
       <button class='btn_remove'>Remove</button>
     </li>
     <li>List Item
        <button class='btn_remove'>Remove</button>
     </li>
  </ul>
  <button id='btn_add'>Add Item</button>
</div>

Now, the Javascript to assign Event Listeners and Handlers:

// Add a list item to the list when Add Item clicked:
<script>
const parent_el = document.getElementById('theList');
const li_content = document.getElementById('item_copy').innerHTML;
const add_btn = document.getElementById('btn_add');

add_btn.addEventListener('click', () => { 
    let created_li = document.createElement('li'); 
    created_li.innerHTML = li_content;
    parent_el.appendChild(created_li); 
});
// Assigns click event listener and handler for the remove buttons currently on the page: 
const remove_btns = document.getElementsByClassName('btn_remove');

// A click on .btn_remove removes item from the list: 
 Array.from(remove_btns).forEach(function(btn) {
     btn.addEventListener('click', (e) => {
     let target_btn = e.target;
     let li_to_remove = target_btn.parentElement;
     li_to_remove.remove();
     });
 });
</script>

In the above example, the remove buttons will not work on list items that are added by the user with the Add Item button.  The reason is because when the Event Listeners were assigned to the Remove buttons, the DOM  Tree did not include the added list items created when the user clicks Add Item.  So the Event Listeners and click handlers don’t exist on the newly created list items.

This is where Event Bubbling can come in to save the day.  You use this process to your advantage to solve this problem by assigning the Event Listener and Handler for the click to the parent element of the user added list items (this would be the <ul> with the id of “theList”).

This way when the user clicks on the remove button on the newly created list item, the click event will bubble up through the parent elements and the Event Listener on <ul> “theList” will be ready and waiting for it.  Once the click on the newly added remove button registers on <ul>, it’s target can be found and the remove element function fired.

Example:

 // Grab the pre-existing parent element (<ul>): 
 const the_List = document.getElementById('theList');
 // Add the listener to #theList and pass in the 
    event:
 the_List.addEventListener('click', (e) => {

 // Check to see what the Event Target of the caught    
    click was.
 // If it was the remove btn, then remove the list
    item:
 if (e.target.className == 'btn_remove') {
     let list_item = e.target.parentElement;
     list_item.remove();
     }
 });

Now, the list items added by the user after the page loads will be removed when the user clicks the remove button.  The <ul> ‘theList’ catches the click event as it bubbles up the DOM tree and handles it by finding the Event Target (the remove button clicked) and removing the parent element of it (the list item).

Hopefully, this summary on Event Bubbling will prove to be helpful to those wanting to get their feet wet in the subject and start to understand what it is and how understanding it can help solve problems like this that come up in your code.

OBJECT ORIENTED PROGRAMMING IN A NUTSHELL

This post is a brief overview of the fundamentals and principles of Object Oriented Prgramming (OOP).  It is a summary of my notes from an online course in PHP (see end of article for reference), so most of the examples are in PHP, but the principles are universal to OOP.

OOP In a Nutshell:

  • OOP (Object Oriented Programming) refers to a method of programming that works with data which is  grouped into a set called an ‘Object’.   
  • The Object can have properties (stored data) and/or methods (functions that the object can run and call).
  • The Object can be based on a blueprint or parent which defines properties and methods it inherits and has access to and can use (further abstracted and managed by an Interface in some cases).  An example of a blueprint or parent that Objects inherit from would be Classes.

That’s just the tip of the tip of the iceberg.  If your interested in the rest of the tip of the iceberg, then here is some more information:

Definitions:

  • Object: A set of data grouped together by a common theme.  An object could be stored in a variable, function or data structure.  Objects consist of key/value pairs (the key is a placeholder(or representative name) for data, and the value is the actual data stored and associated with the key).
  • Class: Describes the properties and methods of an object (it is like a blueprint or definition of an object). Properties can be variables, arrays, or data;  Methods are functions that create/define behaviors of the object.
  • Property: A key/value pair in an Object that stores descriptive data (for example, an Object holding data about a person could have a property key of ‘name’, which would hold the person’s name as the value).
  • Method: A key/value pair in an Object that stores behavioral data (i.e. a function that does something – for example, modifies some property data, or gets additional data and uses it somehow).  The term ‘Method‘ and ‘Function‘ mean basically the same thing.  When talking about Objects, a ‘Method‘ is basically a function that is stored inside of and can be called from an Object.
  • Instantiation: calling the class with the new keyword to make the properties and methods accessible to an object that is created (by assigning a variable to it).  Example:  $obj = new Class_name();
  • Instance: an object (represented by a variable, for example) that has access to and references  the properties and methods of a parent class.  The instance is created through the process of instantiation (using the new keyword; see above).  In other words, an object is an instance of a class.

Benefits of using OOP (Object Oriented Programming):

  • Enables modular functionality in code.  Complex functionality can be accomplished while simplifying the code and making it cleaner (easier to read and understand).
  • Updating the code or modifying and adding features and functionality is also made easier by using OOP.

CLASSES:

  • To create a Class use the class keyword, then make a name:

Note: The first letter of the name of the class must be CAPITALIZED!

Example (A Class named Car is created and a property and method are assigned to it):

class Car {
//Methods and properties go here;
//Example property:
     var $doors = 4;
//Example method:
     function moveWheels(){
         echo "Wheels are moving!";
     }
}
Other things to note in class creation:
  • When creating a class, create the properties before creating the
    methods.
  • Use the keyword var to create properties (you can assign values or not).
  • You can use method_exists(“methodName”); for debugging if trying to find methods in a lot of code.
Creating properties in the class:
  • Use the keyword var to create properties (you can assign values or not):

Example (the class Car is created with properties and methods defined.  The -> is an access operator that is similar to the . in Javascript):

class Car {
    //(properties created with var)
    var $wheels = 4; 
    var $hood = 1;
    var $engine = 1;
    var $doors = 4;

//Methods(functions) in the class:
//To modify or assign values to properties, use $this variable (refers to the object/class that it is in):

    function changeWheels() {
        $this->wheels = 10; 
        //changes the wheels property value.         
        //Note: you don't use the $ when
        //referencing the properties in this
        //function method to set them.
     }

    function moveWheels(){
        echo "Wheels are moving!";
    }
}

OBJECTS:

To use the properties and methods of a class in an object:

  • Create an instance of the class: use the keyword new followed by class_Name(); i.e. new Car(); <—this creates an ‘instance’ of the class.
  • Assign the instance of the class to a variable – the variable now
    stores the instance of the class and is an object that has access to
    properties and methods of the assigned class.

Example:

$hondaFit = new Car(); 
//this creates an instance of the Car class assigned to $hondaFit (which can be called an object).
To access methods/properties:
  • To access a property/method use the -> operator and the name of the property/method (without the $ included) in PHP.  In Javascript, use the . operator (objectName.property):
Example:
  $hondaFit->wheels;  //returns the value.   
//or 
  echo $hondaFit->wheels; //<--this echoes '4'.

//Example (method access): 
  $hondaFit->moveWheels();

//Modify or assign a value to the object property:
  $hondaFit->wheels = 10; 
//reassigns the value of $wheels to 10.

INHERITANCE:

  • A class can inherit and access the properties and methods of other classes by using the extends keyword:

Example:

class Class_A extends Class_B {

//Class_A now has access to props and methods of      //Class_B.

//Props and methods can be added which Class_A will have in addition to those of Class_B.

//you can override the parent (Class_A) property by using var and assigning a new value to it:
var $propNameFromClass_A = newValue;
}

CONSTRUCTORS:

  • Constructor functions execute every time a new instance is created of the parent class they’re created in (with the new keyword).

Examples of practical use:

  • Create default values when a user is created or some default values of a new object that are automatically created when the object is instantiated.
  •  Automatic validations and site maintenance when new objects are created.

Create a constructor in PHP using function, two
underscores, and construct :

Example:

class Class_A {
    function __construct(){
       //code goes here; this runs every time a new
       //instance of Class_A occurs.
    }
}

DATA ACCESSORS:

Three Types:
  • Public — available to the whole program – scope is global.
  • Protected — only available to the parent class or sub-classes
    (extended) that inherit from the parent.
  •  Private — only available to the parent class (not accessible by
    extended classes).

You can use accessors on methods and properties, as well as classes.

Syntax: put the access type (public protected or private) before the class keyword or variable/property name:

Example:

public class Class_A {
    private $prop1 = value; 
    //only accessible inside the class
}

Uses:
-can be used to hide as much of the inner workings of an object as possible. That way it is less likely to break. 
-If you make everything public, then another programmer might alter a variable which you don't want changed by anything other than the inner workings of your object.

STATIC MODIFIERS:

  • This makes a method or property only accessible by the class and not by an instance or object.
  • It allows the use of a property or method of a class without having to
    make an instance of it.
  • Static properties can be referenced in methods inside the class by
    using ClassName::$property

Use the static keyword in place of var:

class Class_A {
    static $property = value; 
//the property is attached to the class and
//not the instance of it.
    function funcName {
    Class_A::$property = newValue; 
    //use :: syntax to access static properties.
    }
}

Note: when accessing static data in the Class, use the $ in the variable name if present (as opposed to omitting it when working with an instance).

To access the static property or method:

Insert :: after the class name to access static data: 

Example: 

echo Class_A::$property;

or

Class_A::funcName(); 
//executes the method using the static property.

S.O.L.I.D. DESIGN PRINCIPLES IN OOP:

  • Fundamental OOP design patterns and concepts to make your code easier to maintain, debug and read.

S.O.L.I.D. stands for:

  • Single Responsibility Principle (SRP): Classes should have one and only one job, or should have one and only one reason to change.
  • Open/Closed Principle (OCP):  Classes/objects should be open for extension, but closed for modification. Easily extend a class without modifying it, make functionality in the class as abstract and broad as possible and leave more specific tasks and computation in the sub-classes that extend it.
  • Liskov Substitution Principle:  Every subclass should be substitutable for their base/parent class. The functionality and methods/properties of a subclass should not remove or significantly differ from the functionality/logic of it’s base/parent class it extends, so that uses of it as a type of the parent class will not break or not work as expected.
  • Interface Segregation Principle (ISP):  No client should be forced to depend on methods it does not use.  Interfaces belong to their clients and not to the implementations. Thus, we should always design them in a way to best suite our clients. we should break our interfaces in many smaller ones, so they better satisfy the exact needs of our clients. Interfaces are just plain function name definitions. There is no implementation of any kind of logic in them.. great advantage of clients depending only and only on what they actually need and use.
    *** ISP recommends that you should use many specialized interfaces instead one big interface. Interfaces belong to their clients and should represent what the clients need. This helps reducing dependencies on methods the client is not using.
  • Dependency Inversion Principle (DIP):  High-level modules should not depend on low-level modules.  Both should depend on abstractions.  Abstractions should not depend upon details. Details should depend upon abstractions.  Common solution is to implement Interfaces which are objects that specify what methods are available to classes or objects that implement them.

DESIGN PATTERNS IN OOP:

  • Singleton:  An object of which there is one and always only one copy or instance.  The object is not instantiated with copies that inherit from it or duplicated anywhere else in the application code.  The purpose of using a singleton could include conserving memory space and provide a single instance of an object that serves as a central and global resource that you need to manage throughout the application (i.e. a log).   The pattern is criticized because since it can expose your object to the global namespace, but if used carefully and depending on the use case, it can be an appropriate solution and pattern to implement.

FURTHER READING AND RESOURCES: 


Helpful Bonus Tips:

  • To check if a Class exists use class_exists("class_Name");  returns a boolean.  Can be used for debugging.
  • You can also use method_exists("method_Name"); to check for a method.  Can be used for debugging if trying to find methods in a lot of code.

This blog post is a summary of my notes taken from an online course on Udemy by Edwin Diaz called PHP for Beginners – Become a PHP Master – CMS Project.  There is a section on Object Oriented Programming in the course that was excellent and explained the fundamental concepts clearly and efficiently.   I’ve tried to boil the concepts down into a quick read as an introductory crash course to get started.