Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
3/27/13
1
Robert Swanson CNX Corpora1on
Chicago, IL
• Briefly discuss the history of JavaScript – How did it evolve? What is it used for today?
– Why should I learn it?
• Review and demysDfy basic JavaScript syntax – Data types, arrays, condiDons, loops – FuncDons and objects – Along the way, we’ll highlight fundamental similariDes to (and differences from) RPG
3/27/13
2
• Learn how to get your hands dirty with JS – IntroducDon to the browser console – Quick and dirty html file execuDon
• JavaScript in AcDon – Discuss where JavaScript “fits in” – See how web pages harness the power of JavaScript frameworks
• Next Steps – Make yourself a master of this exciDng domain!
Staying mindful that this is a 90 minute, “101-level” introduction…
3/27/13
3
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
• “Web 1.0” -‐ staDc HTML and a bunch of links • Needed a richer user interacDon…
– Java applets – LiveScript
• This front-‐end funcDonality was very popular among website developers
• And browser makers were eager to deliver…
JavaScript
Java
JavaScript
(ECMAScript)
3/27/13
4
Browser Wars I: 1996-‐2001 • NetScape vs Microsoe
• JavaScript vs JScript – Messy – IncompaDble – Abused – Bad reputaDon – “Toy Language”
Microsoe won BW I… • IE & JScript evoluDon froze • Standards evolved (ECMA)
• Other browsers caught up to IE
and “Browser Wars II” began…
3/27/13
5
• With AJAX, new ways to harness the power of JavaScript were discovered…
• Today, JavaScript is one of the most popular programming languages in the world
• Browser makers are falling over each other to make JavaScript performance scream
• One interpreter on every machine
• JavaScript has essenDally supplanted Java’s original intent & selling point!
• Worth learning, and you can have fun doing it!
3/27/13
6
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
Client Side Server Side HTTP
3/27/13
7
Client Side HTML CSS JavaScript
Server Side RPG COBOL C / C++ Java PHP (etc)
HTTP
Apa
che
Common “Web 1.0” applicaDons of JavaScript: • Object AnimaDon • Mouse-‐over events • Edit-‐checking • Text manipulaDon • Pop-‐up messages • (etc)
3/27/13
8
Client Side HTML CSS JavaScript
JS Frameworks Ext JS Dojo jQuery (etc)
Server Side RPG COBOL C / C++ Java PHP (etc)
Node.js
J S O N
HTTP
Apa
che
Watch this!!
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
3/27/13
9
• String • Number
• Boolean • Null • Undefined
“Hello, I’m a text string!”
1, 2.5, -‐30, 4e25, Infinity
true, false
‘The text string says, “Hello!” ’
• No “D Specs” in JavaScript!
• Use the “var” statement to declare variables var greeting = “Hello, how are you?”;!
• You can then use “typeof” to interrogate the type typeof greeting;! “string”!
3/27/13
10
CauDon! Unlike RPG, case maqers!
var greeting = “Hello, how are you?”;!typeof greeting;! “string”!
typeof Greeting;! “undefined”!
• Arrays are idenDfied using [square brackets] • First element is 0 (unlike RPG, where it’s 1)
var value = [‘first’, ‘second’, ‘third’];!
value[0];! “first” !
value[1];! “second”!
value[3]=‘fourth’;!
3/27/13
11
Lots of cool tricks you can do with arrays…
array.pop() – “pops” off element(s) from the end
var alpha = [‘a’, ‘b’, ‘c’, ‘d’];!
alpha.pop(1);! “d”!
alpha;! [“a”, “b”, “c”] !
Lots of cool tricks you can do with arrays…
array.shie() – “shie” out element(s) from the start
var alpha = [‘a’, ‘b’, ‘c’, ‘d’];!
alpha.shift(1);! “a”!
alpha;! [“b”, “c”, “d”] !
3/27/13
12
Lots of cool tricks you can do with arrays…
array.unshie() – “shie in” element(s) at the start
var alpha = [‘a’, ‘b’, ‘c’, ‘d’];!
alpha.unshift(‘x’);! 5!
alpha;! [“x”, “a”, “b”, “c”, “d”] !
Lots of cool tricks you can do with arrays…
array.push() – “push” element(s) at the end
var alpha = [‘a’, ‘b’, ‘c’, ‘d’];!
alpha.push(‘x’);! 5!
alpha;! [“a”, “b”, “c”, “d”, “x”] !
3/27/13
13
Lots of cool tricks you can do with arrays…
array.sort() / array.reverse()
var alpha = [‘a’, ‘b’, ‘c’, ‘d’];!
alpha.reverse();! [“d”, “c”, “b”, “a”]!
alpha.sort();! [“a”, “b”, “c”, “d”] !
Lots of cool tricks you can do with arrays…
array.slice() – return a “slice” of the array
var alpha = [‘a’, ‘b’, ‘c’, ‘d’];!
alpha.slice(1,3);! [“b”, “c”]!
alpha;! [“a”, “b”, “c”, “d”] !
3/27/13
14
Lots of cool tricks you can do with arrays…
array.splice() – “splice in” element(s)
var alpha = [‘a’, ‘b’, ‘c’, ‘d’];!
alpha.splice(1,2,’x’,’y’,’z’);! [“b”, “c”]!
alpha;! [“a”, “x”, “y”, “z”, “d”] !
Standard “if” statement… RPG: if x>100;! message=‘too much!’;!else;! message=‘looks good.’;!endif;!
JavaScript: if (x>100) {! message=‘too much!’;!} else {! message=‘looks good.’;!}!
JavaScript Jock: message = (x>100) ? ‘too much!’ : ‘looks good.’;!
3/27/13
15
Comparison Operators
Operator Descrip1on RPG
== Is equal to n/a
=== Is exactly equal to (value and type) =
!= Is not equal to n/a
!== Is not exactly equal to (value and type) <>
> Is greater than >
< Is less than <
>= Is greater than or equal to >=
<= Is less than or equal to <=
&& Logical AND and
|| Logical OR or
Watch for assignment versus comparison when using the equals sign in JavaScript…
Assignment: if (x=‘1’) {}; -‐-‐ this would actually assign a value of ‘1’ to x!
Comparison: x==1; “true” -‐-‐ value converted to numeric then checked
x===1; “false” -‐-‐ value and type are both checked
Generally speaking, best to sDck to ===
3/27/13
16
JavaScript also supports “truthy” and “falsy”…
“Falsy” values (all evaluate to false if tested):
false 0 (zero) “” (empty string)
Null, undefined, NaN
All other values are considered “truthy”
var x=0; // (or could be x=‘’)!var y=‘hi’; // (or could be y=10)!if (x) {! // this code is not executed! alert(‘x is truthy’);!}!if (y) {! // this code is executed! alert(‘y is truthy’);!}!
3/27/13
17
switch statement (“SELECT” in RPG)…
RPG: x=1;!select x;! when 0;! message=‘zero’;! when 1;! message=‘one’;! other;! message=‘I dunno!’;!endsl;!
JavaScript: var x=1;!switch (x) {! case 0:! message=‘zero’;! break;! case 1:! message=‘one’;! break;! default:! message=‘I dunno!’;!}!
switch statement (“SELECT” in RPG) – complex…
RPG: x=1;!select;! when x=0;! message=‘zero’;! when x>=1;! message=‘one+’;! other;! message=‘I dunno!’;!endsl;!
JavaScript: var x=1;!switch (true) {! case (x===0):! message=‘zero’;! break;! case (x>=1):! message=‘one+’;! break;! default:! message=‘I dunno!’;!}!
3/27/13
18
• JavaScript has four types of loops… – While
– Do-‐while
– For
– For-‐in
• While loops are the simplest…
JavaScript var i=0;!while (i<10) {! // do something! i+=1;!}!
RPG i=0;!dow i<10;! // do something! i+=1;!enddo;!
i++;
3/27/13
19
• Do-‐While loops are more like “Do UnDl” in RPG
JavaScript var i=0;!do {! // do something! i++;!} while (i<10)!
RPG i=0;!dou i=10;! // do something! i+=1;!enddo;!
• For loops are the most widely used in JavaScript
JavaScript for (var i=1; i<=10; i++) {! // do something!}!
RPG for i = 1 to 10 by 1;! // do something!endfor;!
3/27/13
20
• For-‐in loops are unique to JavaScript • Niey way to loop through arrays
var alpha=[‘a‘, ‘b‘, ‘c‘, ‘x‘, ‘y‘, ‘z‘];!var result=‘‘, i=0;!for (i in alpha) {! result+= ‘i#‘ + i + ’: ‘ + alpha[i] +’ ... ‘;!}!
result!”i#0: a ... i#1: b ... i#2: c ... i#3:!
RPG: %char(i) !
3/27/13
21
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
• Google Chrome Console – Control-‐Shie-‐J on Windows
– Command-‐opDon-‐J on Mac
You can also use Firebug on Firefox, or the integrated console in IE8+, but Chrome seems to be the front-‐runner in the Browser Wars (at least for now)
3/27/13
22
Let’s try it…
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
3/27/13
23
• Analogous to RPG subprocedures
JavaScript function sum(p1,p2) {! var total = p1+p2;! return total;!}!
RPG p b!d sum pi!d p1 5s 0!d p2 5s 0!d total s 5s 0! /free! total = p1+p2;! return total;! /end-free!p e!
• FuncDons always return a single value. – If no “return” specified, then “undefined” is returned implicitly
– MulDple values can be returned as an array
• “Call a subprocedure” = “Invoke a funcDon”
var result = sum(1,2);!
result! 3 !
3/27/13
24
• Aqempt to pass extra parms? – RPG gives a compile-‐Dme error
– JavaScript just ignores them
var result = sum(1,2,3,4,5);!
result! 3 !
• Pass too few parms? – RPG produces a run-‐Dme “pointer/parameter error” if program tries to access any of the omiqed parms
– JavaScript assigns “undefined” to omiqed parms, resulDng in strange things if code doesn’t watch for it
sum(1)! NaN
• “Parms” oeen referred to as “Arguments” • %parms in RPG = arguments.length in JS
3/27/13
25
function sumOnSteroids() {! var i=0, total=0;! var parmCount = arguments.length;! for (i=0; i<parmCount; i++) {! total += arguments[i];! }! return total;!}!
sumOnSteroids(1,2,3,4,5)! 15
JavaScript also includes a number of pre-‐defined funcDons, such as:
• parseInt() – parses out a number from a string
• parseFloat() – same as parseInt but w/ decimals
• isNaN() – checks if string is Not a Number
• alert() – quick and dirty message box
3/27/13
26
• Almost everything in JavaScript is an “object” – Strings – Numbers – Arrays – FuncDons
• An object is a special kind of data, each with – ProperDes – Methods
• JavaScript also lets you create your own objects
Let’s create an object…
var vehicle = {! make: ‘Ford’,! model: ‘F150’,! color: ‘Silver’! };!
vehicle.make! ”Ford”!
properties
object
3/27/13
27
You can also have objects within objects…
var vehicle = {! make: ‘Ford’,! model: ‘F150’,! color: ‘Silver’,! engine: {! fuelType: ‘diesel’,! valves: 8!! }! };!
A property with a funcDon is a method…
var vehicle = {! make: ‘Ford’,! model: ‘F150’,! color: ‘Silver’,! honk: function(){ ! alert(‘beep-beep!’);! }! };!
3/27/13
28
“this” is oeen used to access object properDes
var vehicle = {! make: ‘Ford’,! model: ‘F150’,! color: ‘Silver’,! honk: function(){ ! alert(‘beep-beep goes the ’! +this.make+’ ‘+this.model);! }! };!
Let’s try it…
3/27/13
29
• Can go in an .html file (i.e., index.html) • <script> tag denotes JavaScript secDon <script>!
// JavaScript code goes here!</script>!
• Script tag can also reference an external .js file <script src=“/myFolder/myApp/app.js”>!
Let’s try it… !
type=“text/javascript”>!<script!
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
3/27/13
30
JavaScript
Data Types, Arrays, Conditions, Loops, Functions, Objects….
?
Server
JSON
• Stands for JavaScript Object NotaDon • Text-‐based data interchange format
• Similar to XML in theory
• Lightweight, meaning smaller number of characters
• Na1ve way of sending data to JavaScript objects
3/27/13
31
Client Side HTML CSS JavaScript
JS Frameworks Ext JS Dojo jQuery (etc)
Server Side RPG COBOL C / C++ Java PHP (etc)
node.js
J S O N
HTTP
Apa
che
Customer Master Record Data:
{“CUSNUM”:123456, “CUSNAME”:“HOME DEPOT”}!
JSON string starts with a curly bracket
Field name, which should always be specified within quotes
Field value, which should be in quotes for strings; no quotes for numeric values
Commas separate each name/value pair
Colons separate name and value
Closing curly bracket denotes end of JSON string
Continue specifying name/value pairs until all fields of your record are represented
3/27/13
32
Customer Master Record Data:
{“CUSNUM”:123456, “CUSNAME”:“HOME DEPOT”,!“ADDRESS”:”101 MAIN ST”, “CITY”:”AUSTIN”,!“STATE”:”TX”, ”SALES”:91386.12}!
Continue specifying name/value pairs until all fields of your record are represented
{“CUSTOMERS”:[ {“CUSNUM”:123456, “CUSNAME”:“HOME DEPOT”}, {“CUSNUM”:987654, “CUSNAME”:“MENARDS”},!
{“CUSNUM”:369468, “CUSNAME”:”LOWES”}!]}!
JSON string starts with a curly bracket
Hard bracket opens the array
Comma separates each record
Array name, followed by a colon
Hard bracket closes the array, immediately followed by a curly bracket to end the JSON string
3/27/13
33
• JSON is naDve to the front-‐end JavaScript – Immediately available for use in the program,
i.e.: CUSTOMERS[1].CUSNAME!
• Back-‐end program (RPG) will need to… – Receive JSON string from the browser – Deconstruct JSON and place values into variables – Do its thing (business logic) – Convert output data back into a JSON string – Send it on to the browser
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
3/27/13
34
• Asnychronous processing gives JavaScript a lot of power (AJAX)
• It can also be confusing when you’re used to the serial/sequenDal processing world
Classic RPG Green Screen Program…
• Load subfile records • Populate header fields • EXFMT – wait for user
• Proceed…
3/27/13
35
Web 1.0 / “Page-‐at-‐a-‐Time”
• Server constructs HTML, sends page to browser
• Program terminates
• AcDon taken by user • Rinse, Repeat
• JavaScript sent to browser, executes to create page
• User takes acDon(s) • MulDple programs called asynchronously to respond with data as needed
“Web 2.0” / Asynchronous JavaScript App
3/27/13
36
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
• JavaScript code is quite powerful • Render & manipulate enDre web pages
• CollecDons of JavaScript widgets and funcDons, aka JavaScript Frameworks, make the whole process much easier
3/27/13
37
Popular Frameworks include… • jQuery • Ext JS • Dojo • Prototype • MooTools
• Countless others
Just about every kind of component imaginable…
3/27/13
38
• Frameworks make tricky HTML concepts easier to build by using small pieces of JavaScript
• For example, a dynamic grid….
HTML for dynamic grid… <div id="example-grid">! <div class="x-panel x-grid-with-row-lines x-panel-default x-grid" style="width:540px;height:200px;" id="gridpanel-1009">! <div class="x-grid-header-ct x-docked x-grid-header-ct-default x-docked-top x-grid-header-ct-docked-top x-grid-header-ct-default-docked-top x-box-layout-ct" style="border-width: 1px; width: 540px; left: 0px; top: 0px;" id="headercontainer-1010">! <div id="headercontainer-1010-innerCt" class="x-box-inner " role="presentation" style="width: 538px; height: 22px;">! <div id="headercontainer-1010-targetEl" style="position: absolute; width: 538px; left: 0px; top: 0px; height: 1px;">! <div class="x-unselectable x-column-header-align-left x-box-item x-column-header x-unselectable-default x-column-header-sort-undefined x-column-header-first x-column-header-sort-DESC" style="border-width: 1px; height: auto; left: 0px; margin: 0px; width: 143px; top: 0px;" id="gridcolumn-1011"><div id="gridcolumn-1011-titleEl" class="x-column-header-inner" style="height: auto; padding-
3/27/13
39
// create the grid!var grid = Ext.create('Ext.grid.Panel', {! store: myStore,! columns: [! {text: ‘Author’, flex: 1, dataIndex: 'Author', sortable: true},! {text: ‘Title’, width: 180, dataIndex: 'Title', sortable: true},! {text: ‘Manufacturer’, width: 115, dataIndex: 'Manufacturer',! sortable: true},! {text: ‘Product Group’, width: 100, dataIndex: 'ProductGroup’,! sortable: true}! ],! width: 540,! height: 200!});!
Ext JS for dynamic grid…
192.168.30.25:7032
IBM i Browser
Login Page
3/27/13
40
Login info
IBM i Browser
Navigation Tree
Click on app
IBM i Browser
JavaScript Program
3/27/13
41
“Web 2.0” / Asynchronous App (RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
(RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
(RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
(RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
(RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
(RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
(RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
(RCV)!----------- !-----------!-----------!-----------!-----------!-----------!-----------!
(SND)!*INLR!
JSON
JSON
JSON
JSON
rpgPgm=‘CM1000’; action=‘getCustMast’;
cusno=12758;
Ajax
JSON
Validate Data Check Security Set LibList Override User
action=vvIn_char(‘action’);!if action=‘getCustMast’;! cusno=vvIn_num(‘cusno’);! chain cusno cmast100 CMds;! vvOut.object=‘cmast100’;! vvOut_toJSON(vvOut:%addr(CMds);!endif;!
JSON
CM1000:
3/27/13
42
• What is JavaScript?
• Where JavaScript is Used • Data Types, Arrays, CondiDons and Loops
• Fire Up the Browser! • FuncDons and Objects
• JavaScript Object NotaDon (JSON)
• Understanding Asynchronous Apps • JavaScript Frameworks Explained
• Wrap-‐Up and Next Steps for Learning
• History of JavaScript • Where JavaScript “fits” in the Web 2.0 World
• Data types, arrays, condiDons and loops • Objects and funcDons • How to experiment in browser console
• JSON and AJAX and asynchronous apps • JavaScript Frameworks
3/27/13
43
• Read! – Object Oriented JavaScript (Stoyan Stefanov)
– On-‐Line Tutorials (w3schools.com)
• Experiment! – Play in your browser & console – Try out a framework (Valence ideal for RPGers)
• Consider formal class training – CNX offers several RPG-‐centric JavaScript courses
Client Side HTML CSS JavaScript
JS Frameworks Ext JS Dojo jQuery (etc)
Server Side RPG COBOL C / C++ Java PHP (etc)
J S O N
HTTP
Apa
che