Download presentation
Presentation is loading. Please wait.
Published byByron Dorsey Modified over 9 years ago
1
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 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
2
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?
3
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 JS Jasmine/TDD is just as important for JS as for server Jury still out on server-side JS 3
4
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
5
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 supportSudoku Standalone rich client apps (Google Docs) Server-side apps (Node.js)
6
Graceful Degradation for SaaS-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
7
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.
8
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
9 END
10
(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
11 END
12
Client-Side JavaScript for Ruby Programmers (ESaaS §6.2) © 2013 Armando Fox & David Patterson, all rights reserved
13
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
14
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 14
15
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 ) Why use helper vs explicit tag? asset pipeline Best practice: JS code in multiple separate files
16
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
17 END
18
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
19 END
20
Optional Aside Another RESTful front end for ugly website http://pastebin.com/LbhCKtRf
21
Functions (ESaaS §6.3) © 2013 Armando Fox & David Patterson, all rights reserved
22
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
23
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
24 END
25
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 They can be anonymous ☐ ☐ ☐ ☐ 25 Which is NOT true about functions in JavaScript?
26
26 END
27
Apple Newton (c. 1997)
28
“Constructor-style” Functions (ESaaS §6.3) © 2013 Armando Fox & David Patterson, all rights reserved
29
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
30
“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
31
31 END
32
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
33 END
34
The Document Object Model (DOM) & jQuery (ESaaS §6.4) © 2013 Armando Fox & David Patterson, all rights reserved
35
e.childNodes DOM Example This is your last chance! e = document.getElementById('notice'); element p attributes: { id: 'notice' } element p attributes: { id: 'notice' } element span attributes: { class: 'warn' } element span attributes: { class: 'warn' } text nodeValue: “This is your” text nodeValue: “This is your” text nodeValue: “chance!” text nodeValue: “chance!” text nodeValue: “last” text nodeValue: “last”
36
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!
37
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 = $(' '); Resulting elements have jQuery superpowers!
38
38 Engineering Software as a Service, Fig 6.8
39
39 END
40
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 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
41 END
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.