javascript: the big picture (esaas §6.1) javascript had to “look like java” only less so - be...
TRANSCRIPT
JavaScript: the Big Picture(ESaaS §6.1)
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.
- Brendan Eich
Image: Wikimedia. Used under CC-SA license.
© 2013 Armando Fox & David Patterson, all rights reserved
Goal
• 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 non-condescending approach to JS
jQuery is the way to do client-side JSJasmine/TDD is just as important for
JS as for serverJury 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 JavaScript Today
• Enhance client part of SaaS-centric app• “Single-page apps”
– Pivotal Tracker: still heavy server support– Sudoku: minimal/no server support
• Standalone rich client apps (Google Docs)• Server-side apps (Node.js)
Graceful Degradation forSaaS-Centric Apps
• Browsers with JS disabled (“legacy browsers”) should get a usable experience– should be easy with RESTful interface
• 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 is 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
9
END
(a) & (b) only
(b) & (c) only
(a) only
(a), (b) and (c)☐
☐
☐
☐
10
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
11
END
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 propertiesvar 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 1st 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
14
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 pipelineBest 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!
16
17
END
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)
1. Depends on the browser implementation
18
If you manually open two separate browser windows, can JavaScript code loaded into one of those windows affect the other window?
19
END
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) 10times3.call(null, 5) 15
Functions as Properties
RP = {};RP.setup = function() { // add invisible 'div' to end of page:};RP.getMovieInfo = function() { // etc.};
23
RP = { setup: function() { // add invisible 'div' to end of page: }, getMovieInfo: function() { // etc. }}
24
END
They always return a value, even if that value might be undefinedThey can be passed a function as an argumentThey can execute concurrently with other functions
They can be anonymous☐
☐
☐
☐
25
Which is NOT true about functions in JavaScript?
26
END
Apple Newton (c. 1997)
“Constructor-style” Functions(ESaaS §6.3)
© 2013 Armando Fox & David Patterson, all rights reserved
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 Functionsa.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
31
END
Square(3).area()
(new Square(3)).area
var p = Square ; (new p(3)).area()
Square(3).area☐
☐
☐
☐
32
var Square = function(side) { this.side = side; this.area = function() { return this.side*this.side; }};
Which call will evaluate to 9?
33
END
The Document Object Model (DOM) & jQuery
(ESaaS §6.4)
© 2013 Armando Fox & David Patterson, all rights reserved
e.childNodes
DOM Example<p id="notice"> This is your <span class="warn">last</span> chance!
</p>e = document.getElementById('notice');
element pattributes: { id: 'notice' }
element spanattributes: { class: 'warn' }
textnodeValue: “This is your”
textnodeValue: “chance!”
textnodeValue: “last”
jQuery
• A powerful framework for DOM manipulation– adds many useful features over browsers’ built-
in 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 elementvar newDiv = $('<div class="main"></div>');
• Resulting elements have jQuery superpowers!
38Eng
inee
ring
Sof
twar
e as
a S
ervi
ce, F
ig
6.8
39
END
JavaScript code can prevent the "Submit" button from submitting the formSome validations may be impractical to perform on client, so must be done on serverThe server doesn’t have to repeat the validations performed by JavaScript
JavaScript code can inspect DOM element attributes to see what the user typed
☐
☐
☐
☐
40
When using JavaScript for client-side form validation, which is NOT true?
41
END