updated js demo readme
This commit is contained in:
Родитель
e54a18b009
Коммит
6a0cee20fe
|
@ -0,0 +1,53 @@
|
|||
import marked, { Renderer } from 'marked';
|
||||
import hljs from 'highlight.js/lib/highlight';
|
||||
import javascript from 'highlight.js/lib/languages/javascript';
|
||||
import typescript from 'highlight.js/lib/languages/typescript';
|
||||
|
||||
hljs.registerLanguage('javascript', javascript);
|
||||
hljs.registerLanguage('typescript', typescript);
|
||||
|
||||
async function run() {
|
||||
const div = document.getElementById('markdownReadme');
|
||||
|
||||
// Create your custom renderer.
|
||||
const renderer = new Renderer();
|
||||
renderer.code = (code, language) => {
|
||||
// Check whether the given language is valid for highlight.js.
|
||||
const validLang = !!(language && hljs.getLanguage(language));
|
||||
// Highlight only if the language is valid.
|
||||
const highlighted = validLang ? hljs.highlight(language, code).value : code;
|
||||
// Render the highlighted code with `hljs` class.
|
||||
return `<pre><code class="hljs ${language}">${highlighted}</code></pre>`;
|
||||
};
|
||||
marked.setOptions({ renderer });
|
||||
|
||||
if (div) {
|
||||
const response = await fetch(div.dataset['src'] || '../README.md');
|
||||
const markdownText = await response.text();
|
||||
div.innerHTML = marked(markdownText, { baseUrl: '../' });
|
||||
restoreScroll(div);
|
||||
|
||||
div.addEventListener('scroll', evt => {
|
||||
saveScroll(div);
|
||||
});
|
||||
|
||||
window.addEventListener('resize', evt => {
|
||||
saveScroll(div);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const scrollKey = `${window.location.pathname}_scrolltop`;
|
||||
|
||||
function saveScroll(div) {
|
||||
window.localStorage.setItem(scrollKey, String(div.scrollTop));
|
||||
}
|
||||
|
||||
function restoreScroll(div) {
|
||||
const scrollTop = window.localStorage.getItem(scrollKey);
|
||||
if (scrollTop) {
|
||||
div.scrollTop = parseInt(scrollTop);
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
|
@ -13,7 +13,6 @@
|
|||
<li class="Tile"><a href="./js-demo/js-demo.html" class="Tile-link">JS Demo</a></li>
|
||||
<li class="Tile"><a href="./js-demo/js-demo-final.html" class="Tile-link">JS Demo Final</a></li>
|
||||
</ul>
|
||||
<div id="markdownReadme"></div>
|
||||
</div>
|
||||
<script src="../assets/scripts.js"></script>
|
||||
</body>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
## JavaScript Demo
|
||||
# JavaScript Demo
|
||||
|
||||
It's entirely possible to create a website with nothing but HTML and CSS, but as soon as you want user interaction other than links and forms, you'll need to reach for JavaScript, the scripting language of the web. Fortunately, JavaScript has grown up quite a bit since it was introduced in the 90s, and now runs just about everything: web applications, mobile applications, native applications, servers, robots and rocket ships.
|
||||
|
||||
|
@ -14,15 +14,18 @@ In this demo we are going to cover a few of the core basics of the language that
|
|||
By the end of the demo we'll have covered the following:
|
||||
|
||||
- Variables
|
||||
- Eventing
|
||||
- Functions
|
||||
- Conditionals
|
||||
- Loops
|
||||
- Interacting with the DOM (Document Object Model)
|
||||
|
||||
### Introduction To Variables
|
||||
## Introduction To Variables
|
||||
|
||||
We can create a new variable with the keywords `var`, `let`, `const` and use them within our application. These variables can contain one of the following types of values:
|
||||
|
||||
> Use `const` for variables you never expect to change, and `let` for anything else. `var` is mostly out of fasion.
|
||||
|
||||
- **boolean**: `true`, `false`
|
||||
- **number**: `1`, `3.14`
|
||||
- **string**: `'single quotes'`, `"double quotes"`, or `` `backticks` ``
|
||||
|
@ -32,6 +35,19 @@ We can create a new variable with the keywords `var`, `let`, `const` and use the
|
|||
- **null**
|
||||
- **undefined**
|
||||
|
||||
### Variable Examples
|
||||
|
||||
```js
|
||||
let myBoolean = true;
|
||||
let myNumber = 5;
|
||||
let myString = `Using backticks I can reuse other variables ${myNumber}`;
|
||||
let myArray = [1, 'cat', false, myString];
|
||||
let myObject = { key1: 'value1', anotherKey: myArray };
|
||||
let myFunction = function(myNumberParam) {
|
||||
console.log(myNumber + myNumberParam);
|
||||
};
|
||||
```
|
||||
|
||||
> JavaScript is a loosely typed (dynamic) language, so if you initially store a number in a variable (`let myVar = 0`), you can change it to contain a string by simply writing `myVar = 'hello'` without any trouble.
|
||||
|
||||
### Adding Variables
|
||||
|
@ -43,25 +59,71 @@ const match = 'a';
|
|||
let matches = 0;
|
||||
```
|
||||
|
||||
> Note that `const` variables are those that will never change during the duration of your program, whereas `let` can change over time. Our `match` value will stay constant, but our `matches` will increment as we find matches.
|
||||
|
||||
### Functions
|
||||
## Functions
|
||||
|
||||
Functions are reusable pieces of functionality. Functions can take inputs (parameters) and return values (or neither). Functions can be called from within your program, from within other functions, or invoked from within the DOM itself.
|
||||
|
||||
In our example we'll create a function called `displayMatches` (camelCase is typical for functions) and we'll invoke this function every time that our submit button is clicked. For now we'll simply have our function call `console.log` (a function that prints values to the browser console):
|
||||
|
||||
```html
|
||||
<input onclick="displayMatches()" class="submit" value="Submit" type="submit" />
|
||||
```
|
||||
In our example we'll create a function called `displayMatches` (camelCase is typical for functions) and we'll invoke this function every time that our submit button is clicked. For now we'll simply have our function call `alert("I'm Clicked")`, which is a function that creates an alert in your browser.
|
||||
|
||||
```js
|
||||
function displayMatches() {
|
||||
console.log("I'm Clicked");
|
||||
alert("I'm Clicked");
|
||||
}
|
||||
```
|
||||
|
||||
### Iteration
|
||||
## Events
|
||||
|
||||
Functions on their own don't have any affect on the page. When I declare `function displayMatches()` I have only defined the function, I haven't actually triggered it.
|
||||
|
||||
To execute a function we need to attach it to an event. There are a number of possible events: keyboard strokes, mouse clicks, document loading etc...
|
||||
|
||||
### Add Event Listeners
|
||||
|
||||
To attach a function to an event, we use an [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventListener) like this:
|
||||
|
||||
```js
|
||||
window.addEventListener('load', function() {
|
||||
console.log('loaded');
|
||||
});
|
||||
|
||||
window.addEventListener('click', function() {
|
||||
console.log('click');
|
||||
});
|
||||
```
|
||||
|
||||
> The `window` is a reference to the entire HTML document
|
||||
|
||||
### Global Event Handlers
|
||||
|
||||
If this feels a little verbose, you're not alone. Many of the [most common event types](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers) are added as element properties. This way we can set properties like `onload` or `onclick` like this:
|
||||
|
||||
```js
|
||||
window.onload = function() {
|
||||
console.log('loaded!');
|
||||
};
|
||||
window.onclick = function() {
|
||||
console.log('clicked!');
|
||||
};
|
||||
```
|
||||
|
||||
> Note that only a single function can be assigned to `onload`, but many eventListeners can be added to `load`
|
||||
|
||||
In our example we want to trigger a function based on the click of a button. To do this, we first need to get a reference to the button. We can use `querySelector` to get that reference. And then we can set its `onclick` value just like above.
|
||||
|
||||
```js
|
||||
const button = docment.querySelector('.submit');
|
||||
button.onclick = displayMatches();
|
||||
```
|
||||
|
||||
You can also combine these together like this:
|
||||
|
||||
```js
|
||||
docment.querySelector('.submit').onclick = displayMatches();
|
||||
```
|
||||
|
||||
Wire this up and see you function in action!
|
||||
|
||||
## Iteration
|
||||
|
||||
Next we'll update our function to iterate through a string of letters. We loop over each letter using the [`for of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) syntax. We'll use real input later, but for now this verifies that our function is working.
|
||||
|
||||
|
@ -74,7 +136,7 @@ function displayMatches() {
|
|||
}
|
||||
```
|
||||
|
||||
### Conditionals
|
||||
## Conditionals
|
||||
|
||||
Next we want to compare each `letter` with our `match` value, and if they are the same, we will increment our `matches` variable. Remember that `letter = match` would set the `letter` variable to the value in `match`, so to do comparisons, we use the equality operator `==` or the strict equality operator `===`.
|
||||
|
||||
|
@ -92,7 +154,7 @@ function displayMatches() {
|
|||
|
||||
> In JavaScript, it's safest to use strict `===` for comparisons, because `==` will try to convert the operands to the same type. For example, `"1" == 1` is true whereas `"1" === 1` is false, but the behavior in certain other cases is [not what you'd expect](https://www.youtube.com/watch?v=et8xNAc2ic8). (See [this video](https://www.destroyallsoftware.com/talks/wat) for more strange JavaScript behavior.)
|
||||
|
||||
### Interacting with the DOM
|
||||
## Interacting with the DOM
|
||||
|
||||
Now that we have a function performing all of our logic, it's time to connect this to our DOM by using some of the browser's built-in functions.
|
||||
|
||||
|
@ -117,7 +179,7 @@ function displayMatches() {
|
|||
}
|
||||
```
|
||||
|
||||
#### Returning the values to the DOM
|
||||
### Returning the values to the DOM
|
||||
|
||||
Now that we've read values from the DOM and fed that into our matching logic, we are ready to return the number of matches to our app. To do this we first need to grab a reference to our submit button, and since this button has no `id` we are going to use the more modern (IE8+) `querySelector` to get it. This function takes any valid CSS selector and returns the first match found.
|
||||
|
||||
|
|
|
@ -1,14 +1,16 @@
|
|||
## Exercise
|
||||
|
||||
If you don't already have the app running, start it with `npm run static` from the root of the `frontend-bootcamp` folder. Click the "exercise" link under day 1 step 2 to see results.
|
||||
If you don't already have the app running, start it with `npm run static` from the root of the `frontend-bootcamp` folded and go to [Todo HTML/CSS Exercise Page](http://localhost:8080/step1-02/exercise/)
|
||||
|
||||
Open the `index.html` file in this exercise folder.
|
||||
|
||||
1. Add an unordered list with class `todos` to the main section
|
||||
2. Add 4 list items with class `todo` inside of that list with the following content
|
||||
`<label><input type="checkbox" /> <span class="title"> Todo </span> </label>`
|
||||
3. Add a span and a button to your footer
|
||||
4. Span content should be `<i class="remaining">4</i> items left` and button should say `Clear Completed` and have a class of `submit`
|
||||
5. Go into the CSS file and add `display: flex` to the footer. Also add `flex-grow:1` to the span inside of the footer
|
||||
2. Add 4 `list items` (`li`) with class `todo` inside of that list with the following content
|
||||
3. Add this content to each of the 4 list items `<label><input type="checkbox" /> <span class="title"> Todo </span> </label>`
|
||||
4. Add a span and a button to your `footer`
|
||||
5. Span content should be `<i class="remaining">4</i> items left` and button should say `Clear Completed` and have a class of `submit`
|
||||
6. Go into the CSS file and add `display: flex` to the footer. Also add `flex-grow:1` to the span inside of the footer
|
||||
|
||||
> Hint: Look back at the CSS demo to see the various ways you can use selectors to target existing HTML
|
||||
|
||||
> There are many strategies for creating and organizing class names in a large application. This lesson is focused on using CSS selectors, not the optimized way to scale your CSS.
|
||||
> There are many strategies for creating and organizing class names in a large application, like [bem](http://getbem.com/), [OOCSS](http://oocss.org/) and [SMACSS](https://smacss.com/). This lesson is focused on using CSS selectors, not the optimized way to scale your CSS.
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
## Exercise
|
||||
|
||||
If you don't already have the app running, start it with `npm run static` from the root of the `frontend-bootcamp` folder. Click the "exercise" link under day 1 step 3 to see results.
|
||||
Open up the [Todo JavaScript Exercise Page](http://localhost:8080/step1-03/exercise/)
|
||||
|
||||
Open the `index.html` file in this exercise folder.
|
||||
|
||||
### Update Navigation
|
||||
|
||||
|
@ -9,7 +11,7 @@ If you don't already have the app running, start it with `npm run static` from t
|
|||
|
||||
### Complete the `updateRemaining` function
|
||||
|
||||
1. Get a reference to the span with the `remaining` class, and store it in a variable.
|
||||
1. Using `querySelector`, get a reference to the span with the `remaining` class, and store it in a variable .
|
||||
2. Use [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) to get all of the todos.
|
||||
3. Set the `innerText` of the remaining span to the length of those todos.
|
||||
4. Add `updateRemaining()` to the end of the `addTodo` function.
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Introduction To React Demo
|
||||
# Step 4 - Introduction To React Demo
|
||||
|
||||
In our last example we saw how we could take a static HTML page and turn it into an interactive page with some buttons and their `onclick` handlers.
|
||||
|
||||
|
@ -6,17 +6,63 @@ In this example we'll see how React turns that paradigm completely around. With
|
|||
|
||||
In this demo we'll be creating a simple counter that will display a count and increment on click.
|
||||
|
||||
## Building
|
||||
## Building the App
|
||||
|
||||
If you already have the app running from a previous step, stop it with `ctrl+C`. Start the app version used in this step by running `npm start` from the root of the `frontend-bootcamp` folder. Click the "demo" link under day 1 step 4 to see results.
|
||||
|
||||
## The App
|
||||
## index.html
|
||||
|
||||
This is the starting point of our React application. It is a component just like the other ones we will be building, but this component will only ever be used once, to render the application. Here's how our app starts out. Let's walk through each line:
|
||||
The `index.html` file in a React project is going to be pretty mimimal. React is loading all of the application onto the page, so the only content you'll find in the page source is a div with an `id` of "app".
|
||||
|
||||
> Note that our bundling tool, webpack, is adding this script tag to the HTML file we provided
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script src="../../step1-04/final/step1-04/final.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## index.tsx
|
||||
|
||||
This is the entry point to your application.
|
||||
|
||||
```ts
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
ReactDOM.render(<p>Hello World</p>, document.getElementById('app'));
|
||||
```
|
||||
|
||||
- `import React from 'react';` - This is how we [import modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) in JavaScript. This line creates a variable in this file called `React` that is equal to the default `export` of the `react` npm module.
|
||||
- `import ReactDOM from "react-dom";` - We've seen React imported before, but now we're also grabbing `ReactDOM` from a package called `react-dom`.
|
||||
- `ReactDOM.render()` - This function is how our code gets on the page. The function takes two parameters, the content to place on the page, and the location that you want it placed.
|
||||
|
||||
## Writing a React Component
|
||||
|
||||
A React component is a piece of code that returns a portion of your application. This can include HTML markup, CSS styles as well as JavaScript driven functionality.
|
||||
|
||||
Components can be created in two ways. The first is method is to use a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), which extends (inherits from) the React.Component class.
|
||||
|
||||
Classes in JavaScript provide a way to collect methods(functions) and properties(values) in an extendable container. We extend React.Container because it provides us with several build in methods, including `render`.
|
||||
|
||||
```jsx
|
||||
import React from 'react';
|
||||
export class App extends React.Component {
|
||||
render() {
|
||||
return <p>Hello World</p>;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Moving our "Hello World" markup into our App's `render` function, we can now update the `ReactDOM.render()` function to look like this
|
||||
|
||||
```jsx
|
||||
ReactDOM.render(<App />, document.getElementById('app'));
|
||||
```
|
||||
|
||||
```jsx
|
||||
export class App extends React.Component {
|
||||
render() {
|
||||
const text = 'My App';
|
||||
|
@ -29,8 +75,8 @@ export class App extends React.Component {
|
|||
}
|
||||
```
|
||||
|
||||
- `import React from 'react';` - This is how we [import modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) in JavaScript. This line creates a variable in this file called `React` that is equal to the default `export` of the `react` npm module.
|
||||
- `export class App` - Just like React exports code, our App component is nothing more than an exported `App` class. This allows us to import the class into other files.
|
||||
- `import React from 'react';` - Each file needs to import React, but only on copy of the code is included in your application.
|
||||
- `export class App` - Just like React exports code, our App component exports a class called `App`. This allows us to import the class into other files.
|
||||
- `extends React.Component` - A JavaScript class is similar to a class in other programming languages (it's a collection of methods and properties). Classes can also be extended, so when we create a React component class, we always extend the base `React.Component` class. (Note that this `Component` class is coming from the `React` variable imported up top.)
|
||||
- `render()` - One of the methods defined by `React.Component` is the `render()` method, which defines the HTML the component is going to render.
|
||||
- `return` - Remember that functions can return values in addition to having side effects, and this component is no different.
|
||||
|
@ -42,23 +88,6 @@ export class App extends React.Component {
|
|||
- Controls can be self-closing: `<div><MyControl text='hi' /></div>`
|
||||
- You can use JavaScript inside of JSX!
|
||||
|
||||
## index.tsx
|
||||
|
||||
This is the file that places your App onto the page.
|
||||
|
||||
```ts
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { App } from './App';
|
||||
ReactDOM.render(<App />, document.getElementById('app'));
|
||||
```
|
||||
|
||||
- `import ReactDOM from "react-dom";` - We've seen React imported before, but now we're also grabbing `ReactDOM` from a package called `react-dom`.
|
||||
> Note that this casing is intentional. Usually, NPM packages are kebab-case and exported items are camelCase or PascalCase. PascalCase is usually used for "proper noun" exports: ProjectName, ComponentName, etc.
|
||||
- `import { App } from './App';` - If we had exported our app using `export default class App extends React.Component`, this line would look similar to the lines above - `import App from './App';`. But the convention for React components is to use named exports, which can easily be extracted using syntax like `{ App }`.
|
||||
> This notation is called [object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring), and it's awesome!
|
||||
- `ReactDOM.render...` - This line calls the render function inside of `ReactDOM` and attaches our `<App />` component to the element with `id=app`. Take a peek in the index.html file. Shouldn't be too hard to find it.
|
||||
|
||||
## Counter Component
|
||||
|
||||
In this example we'll start with an already scaffolded out control. The goal of our counter is to track how many times the counter button is clicked. In the past JavaScript demo we might have accessed the counter element using `document.querySelector('.counter')` and manually incremented the number found there. While using the DOM as your data store works, it's REALLY hard to scale past the most basic demo.
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { App } from './App';
|
||||
ReactDOM.render(<App />, document.getElementById('app'));
|
||||
ReactDOM.render(<p>hello world </p>, document.getElementById('app'));
|
||||
|
|
Загрузка…
Ссылка в новой задаче