Removed multiple non-functional links from README files

pull/1441/head
aryandas2911 2 months ago
parent 38a1bb3c47
commit 3d66dc9d37

@ -1,10 +1,10 @@
# JavaScript Basics: Methods and Functions # JavaScript Basics: Methods and Functions
![JavaScript Basics - Functions](../../sketchnotes/webdev101-js-functions.png) ![JavaScript Basics - Functions](../../sketchnotes/webdev101-js-functions.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## Pre-Lecture Quiz ## Pre-Lecture Quiz
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/9)
When we think about writing code, we always want to ensure our code is readable. While this sounds counterintuitive, code is read many more times than it's written. One core tool in a developer's toolbox to ensure maintainable code is the **function**. When we think about writing code, we always want to ensure our code is readable. While this sounds counterintuitive, code is read many more times than it's written. One core tool in a developer's toolbox to ensure maintainable code is the **function**.
@ -25,8 +25,9 @@ Just as important is the ability to name a function. While this might seem trivi
The syntax for a function looks like the following: The syntax for a function looks like the following:
```javascript ```javascript
function nameOfFunction() { // function definition function nameOfFunction() {
// function definition/body // function definition
// function definition/body
} }
``` ```
@ -34,7 +35,7 @@ If I wanted to create a function to display a greeting, it might look like this:
```javascript ```javascript
function displayGreeting() { function displayGreeting() {
console.log('Hello, world!'); console.log("Hello, world!");
} }
``` ```
@ -62,9 +63,7 @@ To make a function more reusable you'll often want to pass information into it.
Parameters are listed in the definition part within parenthesis and are comma separated like so: Parameters are listed in the definition part within parenthesis and are comma separated like so:
```javascript ```javascript
function name(param, param2, param3) { function name(param, param2, param3) {}
}
``` ```
We can update our `displayGreeting` to accept a name and have that displayed. We can update our `displayGreeting` to accept a name and have that displayed.
@ -79,7 +78,7 @@ function displayGreeting(name) {
When we want to call our function and pass in the parameter, we specify it in the parenthesis. When we want to call our function and pass in the parameter, we specify it in the parenthesis.
```javascript ```javascript
displayGreeting('Christopher'); displayGreeting("Christopher");
// displays "Hello, Christopher!" when run // displays "Hello, Christopher!" when run
``` ```
@ -88,7 +87,7 @@ displayGreeting('Christopher');
We can make our function even more flexible by adding more parameters. But what if we don't want to require every value be specified? Keeping with our greeting example, we could leave name as required (we need to know who we're greeting), but we want to allow the greeting itself to be customized as desired. If someone doesn't want to customize it, we provide a default value instead. To provide a default value to a parameter, we set it much in the same way we set a value for a variable - `parameterName = 'defaultValue'`. To see a full example: We can make our function even more flexible by adding more parameters. But what if we don't want to require every value be specified? Keeping with our greeting example, we could leave name as required (we need to know who we're greeting), but we want to allow the greeting itself to be customized as desired. If someone doesn't want to customize it, we provide a default value instead. To provide a default value to a parameter, we set it much in the same way we set a value for a variable - `parameterName = 'defaultValue'`. To see a full example:
```javascript ```javascript
function displayGreeting(name, salutation='Hello') { function displayGreeting(name, salutation = "Hello") {
console.log(`${salutation}, ${name}`); console.log(`${salutation}, ${name}`);
} }
``` ```
@ -96,10 +95,10 @@ function displayGreeting(name, salutation='Hello') {
When we call the function, we can then decide if we want to set a value for `salutation`. When we call the function, we can then decide if we want to set a value for `salutation`.
```javascript ```javascript
displayGreeting('Christopher'); displayGreeting("Christopher");
// displays "Hello, Christopher" // displays "Hello, Christopher"
displayGreeting('Christopher', 'Hi'); displayGreeting("Christopher", "Hi");
// displays "Hi, Christopher" // displays "Hi, Christopher"
``` ```
@ -113,7 +112,7 @@ If a function does return something then the keyword `return` is used. The `retu
```javascript ```javascript
return myVariable; return myVariable;
``` ```
We could create a function to create a greeting message and return the value back to the caller We could create a function to create a greeting message and return the value back to the caller
@ -127,7 +126,7 @@ function createGreetingMessage(name) {
When calling this function we'll store the value in a variable. This is much the same way we'd set a variable to a static value (like `const name = 'Christopher'`). When calling this function we'll store the value in a variable. This is much the same way we'd set a variable to a static value (like `const name = 'Christopher'`).
```javascript ```javascript
const greetingMessage = createGreetingMessage('Christopher'); const greetingMessage = createGreetingMessage("Christopher");
``` ```
## Functions as parameters for functions ## Functions as parameters for functions
@ -140,7 +139,7 @@ If you run the code below, after 3 seconds you'll see the message **3 seconds ha
```javascript ```javascript
function displayDone() { function displayDone() {
console.log('3 seconds has elapsed'); console.log("3 seconds has elapsed");
} }
// timer value is in milliseconds // timer value is in milliseconds
setTimeout(displayDone, 3000); setTimeout(displayDone, 3000);
@ -155,8 +154,8 @@ When we are passing a function as a parameter we can bypass creating one in adva
Let's rewrite the code above to use an anonymous function: Let's rewrite the code above to use an anonymous function:
```javascript ```javascript
setTimeout(function() { setTimeout(function () {
console.log('3 seconds has elapsed'); console.log("3 seconds has elapsed");
}, 3000); }, 3000);
``` ```
@ -170,7 +169,7 @@ Let's rewrite our code one more time to use a fat arrow function:
```javascript ```javascript
setTimeout(() => { setTimeout(() => {
console.log('3 seconds has elapsed'); console.log("3 seconds has elapsed");
}, 3000); }, 3000);
``` ```
@ -185,7 +184,6 @@ You've now seen we have three ways to pass a function as a parameter and might b
Can you articulate in one sentence the difference between functions and methods? Give it a try! Can you articulate in one sentence the difference between functions and methods? Give it a try!
## Post-Lecture Quiz ## Post-Lecture Quiz
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/10)
## Review & Self Study ## Review & Self Study

@ -1,16 +1,13 @@
# Terrarium Project Part 1: Introduction to HTML # Terrarium Project Part 1: Introduction to HTML
![Introduction to HTML](../../sketchnotes/webdev101-html.png) ![Introduction to HTML](../../sketchnotes/webdev101-html.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## Pre-Lecture Quiz ## Pre-Lecture Quiz
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/15)
> Check out video > Check out video
>
> [![Git and GitHub basics video](https://img.youtube.com/vi/1TvxJKBzhyQ/0.jpg)](https://www.youtube.com/watch?v=1TvxJKBzhyQ) > [![Git and GitHub basics video](https://img.youtube.com/vi/1TvxJKBzhyQ/0.jpg)](https://www.youtube.com/watch?v=1TvxJKBzhyQ)
### Introduction ### Introduction
@ -28,10 +25,11 @@ On your computer, create a folder called 'terrarium' and inside it, a file calle
Or Or
Use these commands on your git bash: Use these commands on your git bash:
* `mkdir terrarium`
* `cd terrarium` - `mkdir terrarium`
* `touch index.html` - `cd terrarium`
* `code index.html` or `nano index.html` - `touch index.html`
- `code index.html` or `nano index.html`
> index.html files indicate to a browser that it is the default file in a folder; URLs such as `https://anysite.com/test` might be built using a folder structure including a folder called `test` with `index.html` inside it; `index.html` doesn't have to show in a URL. > index.html files indicate to a browser that it is the default file in a folder; URLs such as `https://anysite.com/test` might be built using a folder structure including a folder called `test` with `index.html` inside it; `index.html` doesn't have to show in a URL.
@ -62,11 +60,11 @@ Add these lines at the top of your `index.html` file:
The 'head' area of the HTML document includes crucial information about your web page, also known as [metadata](https://developer.mozilla.org/docs/Web/HTML/Element/meta). In our case, we tell the web server to which this page will be sent to be rendered, these four things: The 'head' area of the HTML document includes crucial information about your web page, also known as [metadata](https://developer.mozilla.org/docs/Web/HTML/Element/meta). In our case, we tell the web server to which this page will be sent to be rendered, these four things:
- the page's title - the page's title
- page metadata including: - page metadata including:
- the 'character set', telling about what character encoding is used in the page - the 'character set', telling about what character encoding is used in the page
- browser information, including `x-ua-compatible` which indicates that the IE=edge browser is supported - browser information, including `x-ua-compatible` which indicates that the IE=edge browser is supported
- information about how the viewport should behave when it is loaded. Setting the viewport to have an initial scale of 1 controls the zoom level when the page is first loaded. - information about how the viewport should behave when it is loaded. Setting the viewport to have an initial scale of 1 controls the zoom level when the page is first loaded.
### Task ### Task
@ -74,10 +72,10 @@ Add a 'head' block to your document in between the opening and closing `<html>`
```html ```html
<head> <head>
<title>Welcome to my Virtual Terrarium</title> <title>Welcome to my Virtual Terrarium</title>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
</head> </head>
``` ```
@ -96,13 +94,13 @@ In HTML, you add tags to your .html file to create elements of a web page. Each
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<title>Welcome to my Virtual Terrarium</title> <title>Welcome to my Virtual Terrarium</title>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
</head> </head>
<body></body> <body></body>
</html> </html>
``` ```
@ -120,52 +118,52 @@ Add those plant images into two columns between the `<body></body>` tags:
```html ```html
<div id="page"> <div id="page">
<div id="left-container" class="container"> <div id="left-container" class="container">
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant1" src="./images/plant1.png" /> <img class="plant" alt="plant" id="plant1" src="./images/plant1.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant2" src="./images/plant2.png" /> <img class="plant" alt="plant" id="plant2" src="./images/plant2.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant3" src="./images/plant3.png" /> <img class="plant" alt="plant" id="plant3" src="./images/plant3.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant4" src="./images/plant4.png" /> <img class="plant" alt="plant" id="plant4" src="./images/plant4.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant5" src="./images/plant5.png" /> <img class="plant" alt="plant" id="plant5" src="./images/plant5.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant6" src="./images/plant6.png" /> <img class="plant" alt="plant" id="plant6" src="./images/plant6.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant7" src="./images/plant7.png" /> <img class="plant" alt="plant" id="plant7" src="./images/plant7.png" />
</div> </div>
</div> </div>
<div id="right-container" class="container"> <div id="right-container" class="container">
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant8" src="./images/plant8.png" /> <img class="plant" alt="plant" id="plant8" src="./images/plant8.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant9" src="./images/plant9.png" /> <img class="plant" alt="plant" id="plant9" src="./images/plant9.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant10" src="./images/plant10.png" /> <img class="plant" alt="plant" id="plant10" src="./images/plant10.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant11" src="./images/plant11.png" /> <img class="plant" alt="plant" id="plant11" src="./images/plant11.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant12" src="./images/plant12.png" /> <img class="plant" alt="plant" id="plant12" src="./images/plant12.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant13" src="./images/plant13.png" /> <img class="plant" alt="plant" id="plant13" src="./images/plant13.png" />
</div> </div>
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant14" src="./images/plant14.png" /> <img class="plant" alt="plant" id="plant14" src="./images/plant14.png" />
</div> </div>
</div> </div>
</div> </div>
``` ```
@ -203,13 +201,13 @@ Add this markup above the last `</div>` tag:
```html ```html
<div id="terrarium"> <div id="terrarium">
<div class="jar-top"></div> <div class="jar-top"></div>
<div class="jar-walls"> <div class="jar-walls">
<div class="jar-glossy-long"></div> <div class="jar-glossy-long"></div>
<div class="jar-glossy-short"></div> <div class="jar-glossy-short"></div>
</div> </div>
<div class="dirt"></div> <div class="dirt"></div>
<div class="jar-bottom"></div> <div class="jar-bottom"></div>
</div> </div>
``` ```
@ -223,15 +221,12 @@ There are some wild 'older' tags in HTML that are still fun to play with, though
## Post-Lecture Quiz ## Post-Lecture Quiz
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/16)
## Review & Self Study ## Review & Self Study
HTML is the 'tried and true' building block system that has helped build the web into what it is today. Learn a little about its history by studying some old and new tags. Can you figure out why some tags were deprecated and some added? What tags might be introduced in the future? HTML is the 'tried and true' building block system that has helped build the web into what it is today. Learn a little about its history by studying some old and new tags. Can you figure out why some tags were deprecated and some added? What tags might be introduced in the future?
Learn more about building sites for the web and mobile devices at [Microsoft Learn](https://docs.microsoft.com/learn/modules/build-simple-website/?WT.mc_id=academic-77807-sagibbon). Learn more about building sites for the web and mobile devices at [Microsoft Learn](https://docs.microsoft.com/learn/modules/build-simple-website/?WT.mc_id=academic-77807-sagibbon).
## Assignment ## Assignment
[Practice your HTML: Build a blog mockup](assignment.md) [Practice your HTML: Build a blog mockup](assignment.md)

@ -1,12 +1,11 @@
# Terrarium Project Part 2: Introduction to CSS # Terrarium Project Part 2: Introduction to CSS
![Introduction to CSS](../../sketchnotes/webdev101-css.png) ![Introduction to CSS](../../sketchnotes/webdev101-css.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## Pre-Lecture Quiz ## Pre-Lecture Quiz
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/17)
### Introduction ### Introduction
CSS, or Cascading Style Sheets, solve an important problem of web development: how to make your web site look nice. Styling your apps makes them more usable and nicer-looking; you can also use CSS to create Responsive Web Design (RWD) - allowing your apps to look good no matter what screen size they are displayed on. CSS is not only about making your app look nice; its spec includes animations and transforms that can enable sophisticated interactions for your apps. The CSS Working Group helps maintain current CSS specifications; you can follow their work at [World Wide Web Consortium's site](https://www.w3.org/Style/CSS/members). CSS, or Cascading Style Sheets, solve an important problem of web development: how to make your web site look nice. Styling your apps makes them more usable and nicer-looking; you can also use CSS to create Responsive Web Design (RWD) - allowing your apps to look good no matter what screen size they are displayed on. CSS is not only about making your app look nice; its spec includes animations and transforms that can enable sophisticated interactions for your apps. The CSS Working Group helps maintain current CSS specifications; you can follow their work at [World Wide Web Consortium's site](https://www.w3.org/Style/CSS/members).
@ -21,7 +20,6 @@ You should have the HTML for your terrarium built and ready to be styled.
> Check out video > Check out video
>
> [![Git and GitHub basics video](https://img.youtube.com/vi/6yIdOIV9p1I/0.jpg)](https://www.youtube.com/watch?v=6yIdOIV9p1I) > [![Git and GitHub basics video](https://img.youtube.com/vi/6yIdOIV9p1I/0.jpg)](https://www.youtube.com/watch?v=6yIdOIV9p1I)
### Task ### Task
@ -141,7 +139,7 @@ Notice that each plant in the HTML markup has a combination of ids and classes.
```html ```html
<div class="plant-holder"> <div class="plant-holder">
<img class="plant" alt="plant" id="plant1" src="./images/plant1.png" /> <img class="plant" alt="plant" id="plant1" src="./images/plant1.png" />
</div> </div>
``` ```
@ -259,8 +257,6 @@ To complete the post-lecture quiz, go through this Learn module: [Style your HTM
## Post-Lecture Quiz ## Post-Lecture Quiz
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/18)
## Review & Self Study ## Review & Self Study
CSS seems deceptively straightforward, but there are many challenges when trying to style an app perfectly for all browsers and all screen sizes. CSS-Grid and Flexbox are tools that have been developed to make the job a little more structured and more reliable. Learn about these tools by playing [Flexbox Froggy](https://flexboxfroggy.com/) and [Grid Garden](https://codepip.com/games/grid-garden/). CSS seems deceptively straightforward, but there are many challenges when trying to style an app perfectly for all browsers and all screen sizes. CSS-Grid and Flexbox are tools that have been developed to make the job a little more structured and more reliable. Learn about these tools by playing [Flexbox Froggy](https://flexboxfroggy.com/) and [Grid Garden](https://codepip.com/games/grid-garden/).

@ -4,11 +4,9 @@
## Pre-Lecture Quiz ## Pre-Lecture Quiz
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/29)
### Inheritance and Composition in game development ### Inheritance and Composition in game development
In earlier lessons, there was not much need to worry about the design architecture of the apps you built, as the projects were very small in scope. However, when your applications grow in size and scope, architectural decisions become a larger concern. There are two major approaches to creating larger applications in JavaScript: *composition* or *inheritance*. There are pros and cons to both but let's explain them from within the context of a game. In earlier lessons, there was not much need to worry about the design architecture of the apps you built, as the projects were very small in scope. However, when your applications grow in size and scope, architectural decisions become a larger concern. There are two major approaches to creating larger applications in JavaScript: _composition_ or _inheritance_. There are pros and cons to both but let's explain them from within the context of a game.
✅ One of the most famous programming books ever written has to do with [design patterns](https://en.wikipedia.org/wiki/Design_Patterns). ✅ One of the most famous programming books ever written has to do with [design patterns](https://en.wikipedia.org/wiki/Design_Patterns).
@ -34,7 +32,6 @@ The idea is to use `classes` in conjunction with `inheritance` to accomplish add
Expressed via code, a game object can typically look like this: Expressed via code, a game object can typically look like this:
```javascript ```javascript
//set up the class GameObject //set up the class GameObject
class GameObject { class GameObject {
constructor(x, y, type) { constructor(x, y, type) {
@ -46,11 +43,11 @@ class GameObject {
//this class will extend the GameObject's inherent class properties //this class will extend the GameObject's inherent class properties
class Movable extends GameObject { class Movable extends GameObject {
constructor(x,y, type) { constructor(x, y, type) {
super(x,y, type) super(x, y, type);
} }
//this movable object can be moved on the screen //this movable object can be moved on the screen
moveTo(x, y) { moveTo(x, y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
@ -59,31 +56,31 @@ class Movable extends GameObject {
//this is a specific class that extends the Movable class, so it can take advantage of all the properties that it inherits //this is a specific class that extends the Movable class, so it can take advantage of all the properties that it inherits
class Hero extends Movable { class Hero extends Movable {
constructor(x,y) { constructor(x, y) {
super(x,y, 'Hero') super(x, y, "Hero");
} }
} }
//this class, on the other hand, only inherits the GameObject properties //this class, on the other hand, only inherits the GameObject properties
class Tree extends GameObject { class Tree extends GameObject {
constructor(x,y) { constructor(x, y) {
super(x,y, 'Tree') super(x, y, "Tree");
} }
} }
//a hero can move... //a hero can move...
const hero = new Hero(); const hero = new Hero();
hero.moveTo(5,5); hero.moveTo(5, 5);
//but a tree cannot //but a tree cannot
const tree = new Tree(); const tree = new Tree();
``` ```
✅ Take a few minutes to re-envision a Pac-Man hero (Inky, Pinky or Blinky, for example) and how it would be written in JavaScript. ✅ Take a few minutes to re-envision a Pac-Man hero (Inky, Pinky or Blinky, for example) and how it would be written in JavaScript.
**Composition** **Composition**
A different way of handling object inheritance is by using *Composition*. Then, objects express their behavior like this: A different way of handling object inheritance is by using _Composition_. Then, objects express their behavior like this:
```javascript ```javascript
//create a constant gameObject //create a constant gameObject
@ -125,7 +122,7 @@ function createStatic(x, y, type) {
const hero = createHero(10,10); const hero = createHero(10,10);
hero.moveTo(5,5); hero.moveTo(5,5);
//and create a static tree which only stands around //and create a static tree which only stands around
const tree = createStatic(0,0, 'Tree'); const tree = createStatic(0,0, 'Tree');
``` ```
**Which pattern should I use?** **Which pattern should I use?**
@ -143,8 +140,8 @@ Another pattern common in game development addresses the problem of handling the
This pattern addresses the idea that the disparate parts of your application shouldn't know about one another. Why is that? It makes it a lot easier to see what's going on in general if various parts are separated. It also makes it easier to suddenly change behavior if you need to. How do we accomplish this? We do this by establishing some concepts: This pattern addresses the idea that the disparate parts of your application shouldn't know about one another. Why is that? It makes it a lot easier to see what's going on in general if various parts are separated. It also makes it easier to suddenly change behavior if you need to. How do we accomplish this? We do this by establishing some concepts:
- **message**: A message is usually a text string accompanied by an optional payload (a piece of data that clarifies what the message is about). A typical message in a game can be `KEY_PRESSED_ENTER`. - **message**: A message is usually a text string accompanied by an optional payload (a piece of data that clarifies what the message is about). A typical message in a game can be `KEY_PRESSED_ENTER`.
- **publisher**: This element *publishes* a message and sends it out to all subscribers. - **publisher**: This element _publishes_ a message and sends it out to all subscribers.
- **subscriber**: This element *listens* to specific messages and carries out some task as the result of receiving this message, such as firing a laser. - **subscriber**: This element _listens_ to specific messages and carries out some task as the result of receiving this message, such as firing a laser.
The implementation is quite small in size but it's a very powerful pattern. Here's how it can be implemented: The implementation is quite small in size but it's a very powerful pattern. Here's how it can be implemented:
@ -154,21 +151,20 @@ class EventEmitter {
constructor() { constructor() {
this.listeners = {}; this.listeners = {};
} }
//when a message is received, let the listener to handle its payload //when a message is received, let the listener to handle its payload
on(message, listener) { on(message, listener) {
if (!this.listeners[message]) { if (!this.listeners[message]) {
this.listeners[message] = []; this.listeners[message] = [];
} }
this.listeners[message].push(listener); this.listeners[message].push(listener);
} }
//when a message is sent, send it to a listener with some payload //when a message is sent, send it to a listener with some payload
emit(message, payload = null) { emit(message, payload = null) {
if (this.listeners[message]) { if (this.listeners[message]) {
this.listeners[message].forEach(l => l(message, payload)) this.listeners[message].forEach((l) => l(message, payload));
} }
} }
} }
``` ```
To use the above code we can create a very small implementation: To use the above code we can create a very small implementation:
@ -176,21 +172,21 @@ To use the above code we can create a very small implementation:
```javascript ```javascript
//set up a message structure //set up a message structure
const Messages = { const Messages = {
HERO_MOVE_LEFT: 'HERO_MOVE_LEFT' HERO_MOVE_LEFT: "HERO_MOVE_LEFT",
}; };
//invoke the eventEmitter you set up above //invoke the eventEmitter you set up above
const eventEmitter = new EventEmitter(); const eventEmitter = new EventEmitter();
//set up a hero //set up a hero
const hero = createHero(0,0); const hero = createHero(0, 0);
//let the eventEmitter know to watch for messages pertaining to the hero moving left, and act on it //let the eventEmitter know to watch for messages pertaining to the hero moving left, and act on it
eventEmitter.on(Messages.HERO_MOVE_LEFT, () => { eventEmitter.on(Messages.HERO_MOVE_LEFT, () => {
hero.move(5,0); hero.move(5, 0);
}); });
//set up the window to listen for the keyup event, specifically if the left arrow is hit, emit a message to move the hero left //set up the window to listen for the keyup event, specifically if the left arrow is hit, emit a message to move the hero left
window.addEventListener('keyup', (evt) => { window.addEventListener("keyup", (evt) => {
if (evt.key === 'ArrowLeft') { if (evt.key === "ArrowLeft") {
eventEmitter.emit(Messages.HERO_MOVE_LEFT) eventEmitter.emit(Messages.HERO_MOVE_LEFT);
} }
}); });
``` ```
@ -199,7 +195,7 @@ Above we connect a keyboard event, `ArrowLeft` and send the `HERO_MOVE_LEFT` mes
```javascript ```javascript
eventEmitter.on(Messages.HERO_MOVE_LEFT, () => { eventEmitter.on(Messages.HERO_MOVE_LEFT, () => {
hero.move(5,0); hero.move(5, 0);
}); });
``` ```
@ -213,8 +209,6 @@ Think about how the pub-sub pattern can enhance a game. Which parts should emit
## Post-Lecture Quiz ## Post-Lecture Quiz
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/30)
## Review & Self Study ## Review & Self Study
Learn more about Pub/Sub by [reading about it](https://docs.microsoft.com/azure/architecture/patterns/publisher-subscriber/?WT.mc_id=academic-77807-sagibbon). Learn more about Pub/Sub by [reading about it](https://docs.microsoft.com/azure/architecture/patterns/publisher-subscriber/?WT.mc_id=academic-77807-sagibbon).

Loading…
Cancel
Save