JavaScript had to look like Java only less so be Java's dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JavaScript would have happened.! JavaScript: the Big Picture (ESaaS 6.1)! 2013 Armando Fox & David Patterson, all rights reserved Image: Wikimedia. Used under CC-SA license.
What moving parts are involved in creating the rich interactive user experiences that characterize JavaScript-intensive sites?! What minimal set of key concepts explains how this works, and which of those concepts do we already know from Ruby/ Rails/SaaS architecture?!
Subjective bias disclaimer# JavaScript doesn t (fully) deserve its bad reputation# ESaaS takes principled and noncondescending approach to JS# jquery is the way to do client-side JS# Jasmine/TDD just as important for JS as for server# Jury still out on server-side JS# 3#
History# 1995: Netscape includes LiveScript JavaScript as browser scripting language# Originally, for simple client-side code such as animations and form input validation# Document Object Model (DOM) lets JavaScript inspect & modify document elements# 1997: standardized as ECMAScript# 1998: Microsoft adds XmlHttpRequest to IE5# 2005: Google Maps, AJAX takes off #
Use cases for JS today# Enhance client part of SaaS-centric app# Single-page apps # Pivotal Tracker: still heavy server support# Sudoku: minimal or no server support# Standalone rich client apps (Google Docs)# Server-side apps (Node.js)#
Graceful degradation for SaaS-centric apps# Browsers with JS disabled ( legacy browsers ) should get a usable experience# should be easy if your app is RESTful already# Conditionally show page elements that require JS# Add elements in a "setup" function in JS# Or, make elements hidden using CSS, then change CSS style in "setup" function#
DOM & JavaScript: Document = tree of objects# DOM is a language-independent, hierarchical representation of HTML or XML document# Browser parses HTML or XML => DOM# JavaScript API (JSAPI) makes DOM data structures accessible from JS code# Inspect DOM element values/attributes# Change values/attributes redisplay# Implemented incompatibly across browsers but jquery framework will help us# JavaScript is just another language; the JSAPI gives it power to script the browser.! JavaScript is a single-threaded language. Therefore all JS interactions with browser must be nonblocking.!
Summary: JavaScript s privileged position# Because it s embedded in browser, JavaScript code can:# 1. be triggered by user-initiated events (mouse down, mouse hover, keypress, )# 2. make HTTP requests to server without triggering page reload# 3. be triggered by network events (e.g. server responds to HTTP request)# 4. examine & modify (causing redisplay) current document#
Client-side JavaScript code can interact with HTML page elements because this functionality: (a) is part of the JavaScript language (b) is part of the browser (c) is provided by the JSAPI (a), (b) and (c) (a) & (b) only (b) & (c) only (a) only 9#
Client-Side JavaScript for Ruby Programmers (ESaaS 6.2)! 2013 Armando Fox & David Patterson, all rights reserved
JavaScript basics# Interpreted, dynamically typed# No classes; prototypal inheritance instead (later)# Basic object type is a hash; keys sometimes called slots or properties var movie={title: 'Up', "releaseinfo": {rating: 'G', year: 2010}} Slot names can always be in quotes; OK to omit if slot name is also a legal JS variable name# Use JavaScript console window in modern browsers to try things interactively#
Variable Scope# var restricts scope of a variable; if absent or used in outermost scope => global (almost never what you want!)# Functions are 1 st class objects and closures! extremely common: passing functions to functions# extremely common: functions as property values (feels like instance methods, though they aren t really)# Best practice: create a single global variable that is an object whose properties are your functions & attributes# 12#
JS, browsers, and scope# The global object defines some constants that are part of JS s runtime environment# this in global scope refers to global object# Each HTML page gets its own JS global object# So each page must separately load any desired JS: = javascript_include_tag 'application' (usually in application.html.haml) <script src="/public/javascripts/application.js"> </script> Why use helper vs explicit tag? asset pipeline Best practice: JS code in multiple separate files#
Beautiful JavaScript?# Use what you already know:! SOFA guidelines# Keep code separate from HTML# Red Green Refactor with Jasmine# Tools that can help further:! JavaScript, The Good Parts (Crockford)# JSLint command-line tool jsl JSHint.com# CodeClimate now supports JavaScript!# 14#
If you manually open two separate browser windows, can JavaScript code loaded into one of those windows affect the other window?# 1. Depends on the browser implementation 2. Yes, because JavaScript can access the DOM via the JSAPI 3. No, because each window has its own global object and therefore its own copy of the interpreter 4. No, because there is no concurrency in JavaScript (only one thread can run at a time) 15#
Optional aside# Another RESTful front end for ugly website# http://pastebin.com/lbhcktrf
Functions (ESaaS 6.3)! 2013 Armando Fox & David Patterson, all rights reserved
Functions are closures# Functions are first class objects & closures! A function is a lambda expression# var make_times = function(mul) { return function(arg) { return arg * mul; } } // or: function make_times(mul) {... } times2 = make_times(2) times3 = make_times(3) times2(5) 10 times3.call(null, 5) 15
Functions as properties# RP = {}; RP.setup = function() { // add invisible 'div' to end of page: }; RP.getMovieInfo = function() { // etc. }; RP = { setup: function() { // add invisible 'div' to end of page: }, getmovieinfo: function() { // etc. } } 19#
Which is NOT true about functions in JavaScript? They can be anonymous They always return a value, even if that value might be undefined They can be passed a function as an argument They can execute concurrently with other functions 20#
Constructor-style Functions (ESaaS 6.3)! 2013 Armando Fox & David Patterson, all rights reserved
Apple Newton (c. 1997)#
Every object has a prototype# No Classes; object inheritance based on prototypes # each newly-created object has a prototype# obj. proto (except in some versions of IE)# when slot lookup fails in an object, its prototype is consulted, and so on up the chain# so object inherits both value-slots and function-slots# Prototypal inheritance or differential inheritance!
Constructor style functions a/k/a JS s single worst design flaw# Call a function using new creates new object (this) whose prototype is whatever the function s prototype is, and returns it# Call a function on that object this is bound to that object (receiver)# Call a function without a receiver this assumed to be Global Object, window Call a constructor-like function without new return value is undefined# http://pastebin.com/srnevh59
var Square = function(side) { this.side = side; this.area = function() { return this.side*this.side; } }; Which call will evaluate to 9?# Square(3).area Square(3).area() (new Square(3)).area var p = Square ; (new p(3)).area() 25#
The Document Object Model (DOM) & jquery (ESaaS 6.4)! 2013 Armando Fox & David Patterson, all rights reserved
DOM Example# <p id="notice"> This is your <span class="warn">last</span> chance! </p> e = document.getelementbyid('notice)'; e.childnodes text! nodevalue: this is your # element p! attributes: { id: 'notice' }# element span! attributes: { class: 'warn' }# text! nodevalue: last # text! nodevalue: # chance #
jquery# A powerful framework for DOM manipulation# adds many useful features over browsers builtin JSAPI# homogenizes incompatible JSAPI s across browsers# Don t forget to load it on every page??! Rails 3 includes by default, or load from Google# Defines a single polymorphic global function jquery(), aliased as $() Four ways to call it keep them straight!#
Way #1 & #2: Select DOM elements, create elements# $() or jquery() with any CSS3 expression# $('#movies'), $('.heading'), $('table') Warning! document.getelementbyid() Equivalent: $(window.document).find(selector) Warning! may return multiple elements, but it s not necessarily a JavaScript array! # but there is an iterator for it# Way #2: Create element var newdiv = $('<div class="main"></div>'); Resulting elements have jquery superpowers!#
Engineering Software as a Service, Fig 6.8 30#
When using JavaScript for client-side form validation, which is NOT true? JavaScript code can inspect DOM element attributes to see what the user typed JavaScript code can prevent the "Submit" button from submitting the form Some validations may be impractical to perform on client, so must be done on server The server doesn t have to repeat the validations performed by JavaScript 31#