More JavaScript

Foundationals 2

Andrew Krawchyk

3/14/15

General Assembly

Agenda

  • Functions
  • Intro to DOM
  • Event Listeners
  • HTML + JS Fun

Functions

KISS Principle

  • Keep it simple stupid
  • Smaller functions
    means smaller bugs
  • Easier to test discrete
    functionality

Patterns

Patterns are reusable templates for developing solutions to common problems

Helps keep related code encapsulated in one namespace

When developing larger applications, organizing code can quickly become a problem.

Graph
|_ App
|_ Drawing
|_ Utils

Notifier
|_ App
|_ Messaging
|_ Scheduling
|_ Utils

App
|_ Graph
|_ Notifier
|_ Utils

Intro to DOM

API for HTML

  • Defined by the W3C
  • Used to represent and
    interact with HTML
  • Specifications exist, but
    vendors implement
    their own versions

DOM

Used as an abstraction for specifying how browsers should model HTML for the vendors that implement them

Tree like structure, starts at the root, HTML

Allows developers access to all the nodes in the document in order to manipulate them

Event listeners

Attached to nodes

  • el.addEventListener(eventName, eventHandler);
  • Similar to jQuery's
    .on('eventName', 'eventHandler');
  • Listeners wait for events to happen to nodes
  • There is an enormous amount of events that can be listened to: https://developer.mozilla.org/en-US/docs/Web/Events

  • When events occur, all listeners are notified of the event

  • Listeners can be removed from nodes
    el.removeEventListener(eventName, eventHandler);

Event Bubbling

  • Events on inner elements bubble up the DOM
  • Listeners notify of events with target property
    var outer = document.getElementById('outer');
    outer.addEventListener('click', function(event) {
      var target = event.target;
      console.log(target.id);
      console.log(event);
    });
  • Kill bubbling with .stopPropagation()

HTML + JS exercise

Flyweight Pattern

JavaScript

By Andrew Krawchyk