JavaScript Foundations

Published on Author craigzearfossLeave a comment

JavaScript

  • Written in 1995 by Bendan Eich at Netscape.
  • Intended as a lightweight alternative to Java applets for smaller bits of interaction and functionality
  • No relationship between JavaScript and Java
  • Interpreted, not compiled

Compiled languages are written in source code that is run through a compiler to create machine-readable object code which is often run through linkers which link the code to other pieces of code that it needs to run. Output of this is the final executable code.

Interpreted languages are processed by immediately.

Compiled languages tend to more speed and power than interpreted languages because of optimizations done during the linking process.

In page:

<script type=”text/javascript”>
    // JavaScript code
</script>

External file:

<script type=”text/javascript” src=”main.js”></script>

Data Types:

  • String
  • Number (There is no difference between integer and float)
  • Boolean
  • undefined (never declared or never assigned a value)
  • null (no value)
  • NaN (not a number)
  • objects (Composite data type)

Variables:

  • Can hold any data type.
  • Must begin with a-z, A-Z, _ or $. Rest of characters can be any of those or numbers.
  • Cannot have the same name as reserved keywords.
  • Generally use camel case.
  • Use names that mean something obvious.

Operators:

  • +, -, *, /, %, +=, -=, *=, /=, %=, ++, —

Math Functions:

  • max, min, sqrt, round, random, etc.

Coersion – if a variable’s type does not match the expected type JavaScript will use type coersion to convert it to the type it needs.

  • undefined = false
  • null = false
  • 0 = false
  • any other number (including negative numbers) = true
  • “” = false
  • “any other string” = true

Strict comparison === does not use coercion.

In a string you can escape quotes (and other characters).

  • \’ – quote
  • \” – double quote
  • \n – new line
  • \\ – backslash

String function examples:

.substring(firstpos, (lastpos+1))
.substr(firstpos, numchars)
.charAt(pos)  - return the character at pos
.indexOf(char)  - return the position of char or -1 if not found
.fromCharCode(keyCode)  - converts key code to a character
.toLowerCase()  - convert string to lowercase
.toUpperCase()  - convert string to uppercase

Functions:

  • Function names have the same conventions as variable names.
  • Variables declared in function are local variables that do not exist outside the function block.

Arrays:

  • Store multiple values in a single variable.
  • Elements are the slots that you store the values in.
  • Elements are referenced by whole numbers; First element is 0.
  • Create array:
    var list = [];   // square brackets
    var list = new Array();
  • Array properties:
    list.length  / the number of items in an array
  • Array methods:
    list.push(comma_separated_list)  // add element to the end of an array
    list.sort()    // sort arrays alphabetically

Composite data types are data that are composed of other pieces of data.

Objects:

  • Objects are composite data types.
  • Create object:
    var person = {};
    
  • Objects can also have functions attached to them. These are often called methods.

An anonymous function has no name.

Object methods are able to access the object that they are attached to with the this keyword.

addEventListener method

  • Has two parameters – 1: event, 2: function – called when the even occurs
  • The function will be passed an event object
  • Example 1:

    document.addEventListener(“click”, onClick);
    
    function onClick(event) {
        doSomething();
    }
    
  • Example 2:

    document.addEventListener(“click”, function(event) {
        doSomething();
    });
    

Common events:

  • mousedown
  • mouseup
  • mousemove
  • click
  • keydown
  • keyup

The DOM (Document Object Models) is the representation of an HTML document where each HTML element is represented by a JavaScript object. The objects are not the elements, but they let you access and manipulate the elements.

The top level object for any HTML page is the window object.

All web pages have:

  1. document.head
  2. document.title
  3. document.body

Strategies to make sure the document has loaded before the JavaScript executes:

  1. Move the JavaScript to just before the closing body tag.
  2. The window load event occurs when the window is fully loaded, including CSS and images so this is not an ideal solution.
    window.addEventListener(“loaded”, function(event) {
        // The whole document is loaded and available now
        doSomething();
    });
  3. The DomContentLoaded event triggers when the HTML document has been completely loaded into the browser and is ready to go. Supported in most browsers. Not support in IE8 and before.

    window.addEventListener(“DomContentLoaded”, function(event) {
        // The HTML document is loaded and available now
        doSomething();
    });
  4. jQuery – This should always work because if a feature is not present in a browser jQuery uses a workaround.
    $(document).ready(function() {
        console.log(
    });

Methods to get document elements

getElementById(id) Returns the first element with a matching id or undefined.
getElementsByClassName(className) Returns an array-like object.
It doesn’t have all of the methods of an array.
getElementsByTagName(tagName) Returns an array-like object.
It doesn’t have all of the methods of an array.
querySelector(cssSelectors) Returns a single element
Not supported in IE7. IE8 only supports CSS2 selectors.
querySelectorAll(cssSelectors) Returns an array-like object.
It doesn’t have all of the methods of an array.
Not supported in IE7. IE8 only supports CSS2 selectors.
jQuery

Element properties

  • .style
  • .background
    .backgroundColor
    .color
    .fontFamily
    .fontSize
    etc.

  • .id
  • .className
    .tagName
    .textContent – if element you select has any child elements it will wipe them out
    .innerHtml – allows you to add child tags of the selected element


Creating, Removing and Repositioning Elements

document.createElement(tagName) creates a new HTML element
element.appendChild(newElement)
element.insertBefore(newElement, referenceElement)
list.removeChild(listItem)
  • Must be called on the parent element that contains the child element that you want to remove.
  • If element is not a child of the reference element it will throw an error.
  • Can check that item is a child with the following code:
    if (listItem.parentElement === list) {
        list.removeChild(listItem);
    }
  • To just remove an element regardless of it’s parent
element.parentElement.removeChild(element) Returns the element that was removed.
element.parentNode This also returns the text nodes so usually use element.Children
element.parentElement
element.childNodes list of all of the element’s child nodes

This also returns the text nodes so usually use element.Children
element.children does not include text nodes
element.firstChild This also returns the text nodes so usually use element.firstElementChild
element.firstElementChild does not include text nodes
element.lastChild This also returns the text nodes so usually use element.lastElementChild
element.lastElementChild does not include text nodes
element.nextSibling This also returns the text nodes so usually use element.nextElementSibling
element.nextElementSibling does not include text nodes
element.previousSibling This also returns the text nodes so usually use element.previousElementSibling
element.previousElementSibling does not include text nodes

Extra text (such as tabs, carriage returns and line feeds) gets PRESERVED by the DOM and in text nodes.

Extra text (such as tabs, carriage returns and line feeds) get IGNORED when the HTML is rendered.

Normally we don’t care about text nodes.

Warning: each document change causes a document reflow which can cause performance problems.

A document fragment is part of an HTML document. Because it is not part of the DOM it does not cause a document reflow.

  • var fragment = new DocumentFragment();

Templates are not a built-in standard part of HTML but they fulfill such an important need that many templating engines have been created.

Templating engines:

  • jQuery tmp – no longer in active development
  • Underscore templates
  • Handlebars.js (Refers to values that can be replaced as expressions.)
  • Mustache.js (Refers to values that can be replaced as tags. {{name}})
  • Batman.js
  • jQuote
  • etc.

In templates you create HTML and use special syntax to specify values that can be replaced during runtime.

Using mustache.js:

  1. Include mustache.js
  2. Create a template
  3. Create a data source
  4. Inject the data into the template
  5. Add the rendered HTML into the page

mustache.js example

// Create the template
var template = “<h1>Hello, {{name}}!</h1>”;

// Define the data
var data = {
    name: “Bob”
}

// Replace the values in the template
var html = Mustache.render(template, data);

// Add the html to the page
var div = document.createElement(“div”):
div.innerHTML = html;
document.body.appendChild(div);

mustache.js array example

var data = {
    “stooges”: [
        “name” : “Larry”,
        “name”: “Moe”,
        “name”: “Curly”
    ]
}

{{#stooges}}
    <b>{{name}}</b>
{{/stooges}}

To put Mustache template in a script tag

<script id=”template” type=”x-tmpl=mustache”>
    <h1>Hello, {{name}}</h1>


var template = document.getElementById(“template”).innerHTML;

You can also use use jQuery to load a Mustache template from an external file.

function loadUser() {
    $.get(“template.mst”, function(template) {
        var rendered = Mustache.render(template, {name: “Bob”});
        $(“#target”).html(rendered);
    });
}

http://workflowy.com

A JavaScript function is synchronous. A server request is asynchronous.

Ajax stands for Asynchronous JavaScript and XML.

There is a restriction against loading JavaScript files from another domain.

Access-Control-Allow-Origin is a setting on the server that can allow requests from a specific domain or wild cards can be used. This setting is off by default.

Access-Control-Allow-Origin = “myserver.com”;

The query string is the data being sent with a request. Often called a key/value list.

A GET request puts its data right on the request url.
You don’t want to send sensitive information in a GET request.

In a POST request the data is sent along with the request but is not part of the url.

  • jQuery will attempt to deserialize the data.
  • The 4th parameter allows you to specify a data type (json or xml).
  • If no data type is specified jQuery will try to determine the data type.

var request = $.get(“http://api.openweathermap.org/data/2.5/weather?q=Boston,ma&units=imperial”, null, null, “json”)
.done(function(data) {
    console.log(data);
})
.fail(function() {
    alert(“Request failed. Try again.”);
});

Serialization / Deserialization – the object is serialized into something that can be transferred across the web and deserialized back into a object.

JSON and XML are used to serialize objects. XML can get a bit verbose.

JSON:

  • Stands for JavaScript Object Notation.
  • Syntax is very similar to JavaScript object notation.
  • Property names need to be strings enclosed in double quotes
  • In JSON you cannot define functions.

  • Can be used across platforms.

When jQuery get receives response that it determines as JSON it attempts to deserialize it to an object. You can tell jQuery what type of data it is receiving and it will respect it.

Web API directory
http://www.programableweb.com/apis/directory

Scope:

  • Scope is the part of the code where a variable is visible and useable.
  • Anything on the window object is global scope and can be accessed without typing “window.”
  • Avoid using global variables.

IIFE (Immediately Invoked Function Expression)

  • Take an anonymous function and wrap it in parenthesis.
    (function() {
        // do something
    })();
    
  • Because it’s anonymous it never goes into global scope

Software Architecture is the high-level structure of an application, it’s different parts and how they work together.


Design Patterns

Design Patterns are common solutions to recurring problems.

UML (Unified Modeling Language) a way to visually show how objects relate to each other.

Observer Pattern

  • Allow certain objects to observe behavior in other objects and react when those changes occur.
  • Subject has a list of observers.
  • var subject = {
        observers: [];
        registerObservers: function observer(observer) {
            this.observers.push(observer);
        },
        unregisterObservers: function observer(observer) {
            // ...
        },
        notifyObservers: function() {
            for (var i=-; i
    
  • The DOM Event Listener is an example of an observer pattern.
  • Tightly coupled code:
    Code throughout the app depends on the rest of the code being in a very specific state.

    - Minor changes in one part of the app can have repercussions all over the place.

Model View Controller Pattern (MVC)

  • An overall pattern for architecting an entire application.
  • Originated with a language called “Smalltalk-80” released in 1980.
  • Model - holds the data used by the application.
  • View - displays the model’s data; responds to user’s input
  • Controller -provides the logic that ties the model and view together.
  • Note the observer pattern that the model is a subject and the view is an observer.
  • MVC variations (Collectively MV*):
  • - Hierarchical MVC (HMVC)

    - Model View Adapter (MVA)

    - Model View Presenter (MVP)

    - Model View View-Model (MVVM)


Frameworks

Frameworks often dictate the structure of your entire application, helping to organize your code logically.

Some JavaScript frameworks:

Ember

  • Designed for making very large, complex web applications.
  • Sites include Yahoo, Groupon, Zendesk, Living Social, etc.
  • Routes map URLs to specific views, templates and models.
  • Each view has it’s own model.
  • Controllers sit between the model and view and are said to decorate the model. (So the controller may change some of the model’s data in some way.)
  • Makes use of binding, a piece of functionality that allows visual items to be bound to (permanently connected) to a piece of data in the model.
  • There is two-way binding which is probably why the controller takes on a lesser role in Ember.
  • There is a steep learning curve.

Angular

  • Sites include YouTube, Ancestry.com, Amazon, etc.
  • Angular uses special HTML attributes called “directives” that allow for template-like formatting in the HTML page itself.
  • Relies heavily on it’s two-way binding.
  • Emphasizes the controllers which provide logic for the application and model objects for the view to bind to.
  • Since it doesn’t impose a structure you can just use specific pieces of it.

Backbone.js

  • Probably has the lowest learning curve.
  • Excellent choice for small applications.
  • Emphasizes models and views.
  • Uses routes for mapping urls to specific parts of an application.
  • Very much like Ember in structure.
  • Doesn’t have built in templating or much in the way of binding but you can use any templating engine.
  • Views are tied to specific elements of the page that listen for changes in the model and then render themselves based on the changes. Can also listen for actions in the view.
  • Models are often tied to web services.
  • No built in controllers.
  • Doesn’t enforce much structure.

Backbone.Model

  • Serves as the basis for the models in your app.
  • Call Backbone.Model.extend to make a custom model for your app.
    var MyModel - Backbone.Model.extend({
        urlRoot: “http://myservice.com”
    });
    
  • Finally, create an instance of your model.
    var appModel = new MyModel();
    
  • Backbone.View
  • Extend and create an instance similar to Backbone.Model
    var MyView - Backbone.View.extend({
        intialize: function() {
            // code to initialize the view
        }
    });
    var someView = new MyView();
    
  • Note that initialize is automatically called when the view instance is created.
  • A
    is created for the view by default. You can also tie it to an existing element by passing it in when the instance is created.

    var div = document.getElementById(“myViewDiv”);
    var someView = new MyView({el: div});
    
  • Backbone has a dependency on underscore-min.js and uses jQuery for server communication.

Leave a Reply

Your email address will not be published. Required fields are marked *