Let’s pick up the 70-480 study guide with the second objective: Implement Program Flow.
Implement program flow
Iterate across collections and array items; manage program decisions by using switch statements, if/then, and operators; evaluate expressions.
- Iterating a collection or array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
- Switch statement
1 2 3 4 5 6 7 8 9 10 11 12 |
|
- If/then/else
1 2 3 4 5 6 7 8 9 |
|
- JavaScript supports a similar set of comparison and assignment operators as other modern languages. Some special ones to watch for:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
- Evaluate expressions
1
|
|
Raise and handle an event
Handle common events exposed by DOM (OnBlur, OnFocus, OnClick); declare and handle bubbled events; handle an event by using an anonymous function
- Handling events
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
The third argument to addEventListener indicates whether you want to get the event in the capture stage. The capture stage begins at the HTML element and progresses through to the target, then the bubble stage flows from the target back to the HTML element. Using a combination of capture and Event.stopPropagation
will allow you to grab an event before it reaches its actual target.
Event.preventDefault can be used to stop the default action from being invoked.
Implement exception handling
Set and respond to error codes; throw an exception; request for null checks; implement try-catch-finally blocks
To set an error:
throw new Error(100, "Yes sir");
Internet Explorer will treat the first argument as error number and second as description. Other browsers may support only a message.
You can get global errors
1 2 3 |
|
Try/catch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Implement a callback
Receive messages from the HTML5 WebSocket API; use jQuery to make an AJAX call; wire up an event; implement a callback by using anonymous functions; handle the “this” pointer
To receive messages from the WebSocket API, first create a new WebSocket object using the ws protocol. Attach event handlers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Making an AJAX call with jQuery is done as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
The ajax method returns a Promise interface (jqXhr in this case), so the event handlers can also be hooked up as:
1 2 3 |
|
The this
pointer was addressed in other study guide posts.
Create a web worker process
Start and stop a web worker; pass data to a web worker; configure timeouts and intervals on the web worker; register an event listener for the web worker; limitations of a web worker
Here is a web worker sample:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Other web worker notes:
- Event data can be an object and is sent a serialized copy - modifying the object in one context will not change it in the other
- The
self
keyword is the global context in the worker js file - There is no DOM, window, or document in the worker script
- The nav, location, XMLHttpRequest, and cache APIs can be accessed