diff --git a/2-ui/2-events/03-event-delegation/4-behavior-tooltip/solution.view/index.html b/2-ui/2-events/03-event-delegation/4-behavior-tooltip/solution.view/index.html index 31d0d46b..1ef37cdc 100644 --- a/2-ui/2-events/03-event-delegation/4-behavior-tooltip/solution.view/index.html +++ b/2-ui/2-events/03-event-delegation/4-behavior-tooltip/solution.view/index.html @@ -15,7 +15,7 @@ border: 1px solid #b3c9ce; border-radius: 4px; text-align: center; - font: italic 14px/1.3 arial, sans-serif; + font: italic 14px/1.3 sans-serif; color: #333; background: #fff; box-shadow: 3px 3px 3px rgba(0, 0, 0, .3); diff --git a/2-ui/2-events/03-event-delegation/4-behavior-tooltip/source.view/index.html b/2-ui/2-events/03-event-delegation/4-behavior-tooltip/source.view/index.html index 57a19d01..add3b214 100644 --- a/2-ui/2-events/03-event-delegation/4-behavior-tooltip/source.view/index.html +++ b/2-ui/2-events/03-event-delegation/4-behavior-tooltip/source.view/index.html @@ -16,7 +16,7 @@ border: 1px solid #b3c9ce; border-radius: 4px; text-align: center; - font: italic 14px/1.3 arial, sans-serif; + font: italic 14px/1.3 sans-serif; color: #333; background: #fff; box-shadow: 3px 3px 3px rgba(0, 0, 0, .3); diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/gallery.css b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/gallery.css index 66690e53..4522006a 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/gallery.css +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/solution.view/gallery.css @@ -1,16 +1,16 @@ body { margin: 0; padding: 0; - font: 75%/120% Arial, Helvetica, sans-serif; + font: 75%/120% sans-serif; } h2 { - font: bold 190%/100% Arial, Helvetica, sans-serif; + font: bold 190%/100% sans-serif; margin: 0 0 .2em; } h2 em { - font: normal 80%/100% Arial, Helvetica, sans-serif; + font: normal 80%/100% sans-serif; color: #999999; } diff --git a/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/gallery.css b/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/gallery.css index 0c5061c2..b6e52301 100644 --- a/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/gallery.css +++ b/2-ui/2-events/04-default-browser-action/3-image-gallery/source.view/gallery.css @@ -1,16 +1,16 @@ body { margin: 0; padding: 0; - font: 75%/120% Arial, Helvetica, sans-serif; + font: 75%/120% sans-serif; } h2 { - font: bold 190%/100% Arial, Helvetica, sans-serif; + font: bold 190%/100% sans-serif; margin: 0 0 .2em; } h2 em { - font: normal 80%/100% Arial, Helvetica, sans-serif; + font: normal 80%/100% sans-serif; color: #999999; } diff --git a/2-ui/2-events/04-default-browser-action/menu.view/menu.css b/2-ui/2-events/04-default-browser-action/menu.view/menu.css index 4c172e05..32494ae9 100644 --- a/2-ui/2-events/04-default-browser-action/menu.view/menu.css +++ b/2-ui/2-events/04-default-browser-action/menu.view/menu.css @@ -9,7 +9,7 @@ outline: none; text-align: center; text-decoration: none; - font: 14px/100% Arial, Helvetica, sans-serif; + font: 14px/100% sans-serif; padding: .5em 2em .55em; text-shadow: 0 1px 1px rgba(0, 0, 0, .3); border-radius: .5em; diff --git a/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/solution.view/index.html b/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/solution.view/index.html index 8fbae4c7..c8e879f2 100644 --- a/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/solution.view/index.html +++ b/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/solution.view/index.html @@ -18,7 +18,7 @@ border: 1px solid #b3c9ce; border-radius: 4px; text-align: center; - font: italic 14px/1.3 arial, sans-serif; + font: italic 14px/1.3 sans-serif; color: #333; background: #fff; box-shadow: 3px 3px 3px rgba(0, 0, 0, .3); diff --git a/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/source.view/index.html b/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/source.view/index.html index 8abb923d..2dc4394e 100644 --- a/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/source.view/index.html +++ b/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/1-behavior-nested-tooltip/source.view/index.html @@ -18,7 +18,7 @@ border: 1px solid #b3c9ce; border-radius: 4px; text-align: center; - font: italic 14px/1.3 arial, sans-serif; + font: italic 14px/1.3 sans-serif; color: #333; background: #fff; box-shadow: 3px 3px 3px rgba(0, 0, 0, .3); diff --git a/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/solution.view/style.css b/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/solution.view/style.css index f0736f3e..fa2f09eb 100644 --- a/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/solution.view/style.css +++ b/2-ui/3-event-details/3-mousemove-mouseover-mouseout-mouseenter-mouseleave/2-hoverintent/solution.view/style.css @@ -30,7 +30,7 @@ body { border: 1px solid #b3c9ce; border-radius: 4px; text-align: center; - font: italic 14px/1.3 arial, sans-serif; + font: italic 14px/1.3 sans-serif; color: #333; background: #fff; z-index: 100000; diff --git a/2-ui/4-forms-controls/2-focus-blur/3-editable-div/solution.view/my.css b/2-ui/4-forms-controls/2-focus-blur/3-editable-div/solution.view/my.css index 10e9ddc2..67905e6d 100644 --- a/2-ui/4-forms-controls/2-focus-blur/3-editable-div/solution.view/my.css +++ b/2-ui/4-forms-controls/2-focus-blur/3-editable-div/solution.view/my.css @@ -2,7 +2,7 @@ .edit { height: 150px; width: 400px; - font-family: arial; + font-family: sans-serif; font-size: 14px; display: block; } diff --git a/2-ui/4-forms-controls/2-focus-blur/3-editable-div/source.view/my.css b/2-ui/4-forms-controls/2-focus-blur/3-editable-div/source.view/my.css index 10e9ddc2..67905e6d 100644 --- a/2-ui/4-forms-controls/2-focus-blur/3-editable-div/source.view/my.css +++ b/2-ui/4-forms-controls/2-focus-blur/3-editable-div/source.view/my.css @@ -2,7 +2,7 @@ .edit { height: 150px; width: 400px; - font-family: arial; + font-family: sans-serif; font-size: 14px; display: block; } diff --git a/archive/01-hello-world/1-hello-alert/solution.md b/archive/01-hello-world/1-hello-alert/solution.md deleted file mode 100644 index e69de29b..00000000 diff --git a/archive/01-hello-world/1-hello-alert/solution.view/index.html b/archive/01-hello-world/1-hello-alert/solution.view/index.html deleted file mode 100644 index 45e6744b..00000000 --- a/archive/01-hello-world/1-hello-alert/solution.view/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/archive/01-hello-world/1-hello-alert/task.md b/archive/01-hello-world/1-hello-alert/task.md deleted file mode 100644 index afed6a91..00000000 --- a/archive/01-hello-world/1-hello-alert/task.md +++ /dev/null @@ -1,12 +0,0 @@ -importance: 5 - ---- - -# Show an alert - -Create a page that shows a message "I'm JavaScript!". - -Do it in a sandbox, or on your hard drive, doesn't matter, just ensure that it works. - -[demo src="solution"] - diff --git a/archive/01-hello-world/article.md b/archive/01-hello-world/article.md deleted file mode 100644 index b08909eb..00000000 --- a/archive/01-hello-world/article.md +++ /dev/null @@ -1,90 +0,0 @@ -# Hello, world! - -About 98% of the tutorial is core Javascript, that is platform-independant. So you'll be able to learn how to use Node.JS and other things based on that knowledge. - -But we need something like a "base environment" to run our scripts, and browser is probably a good choice. - -So we'll start with attaching a script to the webpage. For other environments like Node.JS there are other ways to run it. - -[todo remove defer/async from here and move to 2nd part?] - -## The "script" tag - -[todo need this? and special (need it too?)] -```smart header="What if I want to move faster?" -In the case if you've developed with JavaScript already or have a lot of experience in another language, you can skip detailed explanatins and jump to . There you can find an essense of important features. - -If you have enough time and want to learn things in details then read on :) -``` - -JavaScript programs can be inserted in any place of HTML with the help of the ` -*/!* - -

...After the script.

- - - - -``` - -```online -You can run the example clicking on a "Play" button in it's right-top corner. -``` - -The ` - ``` - - These comments were supposed to hide the code from an old browser that did't understand a ` - - - - \ No newline at end of file diff --git a/archive/02-external-script/1-hello-alert-ext/solution.md b/archive/02-external-script/1-hello-alert-ext/solution.md deleted file mode 100644 index f42c41e6..00000000 --- a/archive/02-external-script/1-hello-alert-ext/solution.md +++ /dev/null @@ -1,8 +0,0 @@ -The HTML code: - -[html src="index.html"] - -For the file `alert.js` in the same folder: - -[js src="alert.js"] - diff --git a/archive/02-external-script/1-hello-alert-ext/task.md b/archive/02-external-script/1-hello-alert-ext/task.md deleted file mode 100644 index fe38de40..00000000 --- a/archive/02-external-script/1-hello-alert-ext/task.md +++ /dev/null @@ -1,9 +0,0 @@ -importance: 5 - ---- - -# Show an alert with an external script - -Take the solution of the previous task . Modify it by extracting the script content into an external file `alert.js`, residing in the same folder. - -Open the page, ensures that the alert works. diff --git a/archive/02-external-script/2-async-defer-first/solution.md b/archive/02-external-script/2-async-defer-first/solution.md deleted file mode 100644 index 0513e5fc..00000000 --- a/archive/02-external-script/2-async-defer-first/solution.md +++ /dev/null @@ -1,5 +0,0 @@ -Answers: - -1. The first is `big.js`, that's a normal sequence for external ` - -``` - -What if we add `async`? - -```html - - -``` - -What if we switch to `defer`? - -```html - - -``` - diff --git a/archive/02-external-script/article.md b/archive/02-external-script/article.md deleted file mode 100644 index 786fb276..00000000 --- a/archive/02-external-script/article.md +++ /dev/null @@ -1,251 +0,0 @@ -# External scripts - -If we have a lot of JavaScript code, we can it put it into a separate file. - -The script file is attached to HTML like this: - -```html - -``` - -Here `/path/to/script.js` is an absolute path to the file with the script (from the site root). - -It is also possible to provide a path relative to the current page. For instance, `src="script.js"` would mean a file `"script.js"` from the current folder. - -We can give a full URL al well, for instance: - -```html - -``` - -To attach several scripts, use multiple tags: - -```html - - -… -``` - -```smart -As a rule, only simplest scripts are put into HTML. More complex ones reside in separate files. - -The benefit of a separate file is that the browser will download it and then store in its [cache](https://en.wikipedia.org/wiki/Web_cache). - -After it, other pages which want the same script will take it from the cache instead of downloading it. So the file is actually downloaded only once. - -That saves traffic and makes pages faster. -``` - -````warn header="If `src` is set, the script content is ignored." -A single ` -``` - -We must choose: either it's an external ` - -``` -```` - -## Asynchronous scripts: defer/async - -Browser loads and shows HTML gradually as it comes. That's clearly noticeable on the slow internet connection. The browser doesn't wait for the page to load fully. It shows the part that has been loaded already, and then adds content to it as it loads. - -As we noted before, when the browser meets a ` -*/!* - -

Rabbits counted!

- - - -``` - -The behavior is called "synchronous". Usually it causes no problems, but there's an important consequence. - -**If a script is external, then until the browser downloads and executes it, a visitor has to wait.** - -So, in this document, until `big.js` loads and executes, the `` content is hidden: - -```html - - -*!* - -*/!* - - - This text is not shown until the browser executes big.js. - - -``` - -The question is -- do we really want the visitor to wait until the script finishes? - -Most of time, we don't. - -Sometimes, a script may contain a very important code that really must be loaded before the rest of the page is parsed (and the scripts below executed). But that's only sometimes. - -Usually a visitor should be able to see the page while the script is loading. That's especially true for sites with an important content (like the tutorial) -- even if some interfaces are yet inactive (scripts not loaded yet), the visitor can read the text and navigate. - -There are situations when such blocking is even dangerous. For example, when we attach a script from the banner system, or a 3rd-party integration code. - -Like this: - -```html run height=100 -Wait. The text below will shown up only after the script executes. - - - - -

…Important information!

-``` - -It's just wrong that the rest of the page is not shown until the banner is loaded. And what if their server is overloaded and responds slowly? Our visitors will have wait even more, maybe even leave for another, faster site. - -So, how to "fix" the blocking behavior? - -Our first attempt could be to put all such scripts to the bottom of the ``, after all content. - -But the solution is not perfect: - -1. The script won't start loading until the HTML loads. If the HTML is large, then the delay may be significant. We'd like the browser to start loading a script early, but still do not block the page. -2. If there are many scripts at the bottom of the page, then they queue up. Browser executes only one ` - -

…Important information!

-``` - -Now if we run it, we'll see that the whole document is displayed immediately, and the external script runs when it loads. - -Let's see more examples with `defer` and `async` to clearly understand the similarities and the differences. - -Both attributes allow the browser to show the page without waiting for the script to load. But... - -1. Deferred scripts keep the relative order, while async scripts do not. - - For example, in the code below (with `async`) there are two scripts. The one which loads first will run first. - - ```html - - - ``` - - If `2.js` is bigger than `1.js`, it may happen that `2.js` will run before `1.js`. That's normal. Async scripts are totally independent. - - And in the code below `defer` is used, which forces browser to keeps execution order. Even if `2.js` loads first, it waits and executes after `1.js`: - - ```html - - - ``` - - This feature of "deferred" scripts is important when `2.js` relies on the result of `1.js` and we must be sure that the order is determined. - -2. A script with `defer` always waits for the HTML-document to fully load. The `async` script runs immediately as it loads. - - For instance, when the document is large, like: - - ```html - - - - A long long text. Many words. - ... - ``` - - ...Here `async.js` executes when it loads -- possibly, before the document is fully loaded. In contrast, `defer.js` always waits for the full document to be ready. - - So, if a script doesn't need the rest of the document (like a web counter), then `async` is superb. And in another case a script may need the whole document to do some work with it. Then `defer` is preferable. - - -```smart header="Either `async` or `defer`" -We can't use both `defer` and `async` on a single script. If we do that, `async` takes precedence, `defer` is ignored. -``` - -```warn header="Attributes `async/defer` are only for external scripts" -The attributes `async/defer` work only when set on a script with `src`. - -On a script without `src` like <script>...</script>, they will be ignored. -``` - - -## Summary - -- Scripts in an external file can be inserted on the page via ``. -- The browser doesn't show the content below the script until it executes. Unless the script has `async` or `defer` attributes. -- Both `async` and `defer` allow the browser to start script loading and then continue to parse/show the page. They only work on external scripts. -- The difference is that `defer` keeps the relative script order and always executes after the document is fully loaded. In contrast, `async` script executes when it loads, without any conditions. - -Before inserting an external ` -[/html] - -The `click` processing order: -
    -
  1. `alert('in onclick')` works.
  2. -
  3. The attribute is changed and the DOM mutation event is processed synchronously, immediately triggering `onchange`. It outputs `alert('onpropchange')`.
  4. -
  5. The rest of `onclick` executes, leading to `alert('out onclick')`.
  6. -
- - -### Nested DOM events are synchronous. - -[summary] -There are methods which trigger an immediate event, like `elem.focus()`. These events are also processed in a synchronous manner. -[/summary] - -Run the example below and click on the button. Notice that `onfocus` -doesn't wait `onclick` to complete, it works immediately. - -[html autorun height=auto] - - - - -[/html] - -In the example above, the alert order is in onclick->focus->out onclick, that clearly demonstrates the synchronous behavior. - -[smart] -The line labelled (*) is required, because `alert(message)` focuses on the message window. When it is disposed, the browser refocuses back. - -So without (*) the `focus` would be triggered one extra time after the alert. -[/smart] - -[summary] -Events are also processed immediately when triggered from JavaScript by `dispatchEvent/fireEvent`. -[/summary] - -Usually event handlers are executed one by one. So we assume that one handler finishes before the other starts. - -**Synchronous events break this one-by-one rule, that may can cause side-effects.** - -For example, the `onfocus` handler may assume that `onclick` has completed the job. - -There are two ways to fix it: -
    -
  1. Move `text.focus()` to the end of the `onclick` code.
  2. -
  3. Wrap `text.focus()` into `setTimeout(.., 0)`: -[js] -button.onclick = function() { - alert(1) - setTimeout(function() { text.focus() }, 0) - alert(2) -} -[/js] -
  4. -
- -The concrete way is chosen according to your architecture. - - -## JavaScript execution and rendering - -[summary]In most browsers, rendering and JavaScript use single event queue. It means that while JavaScript is running, no rendering occurs.[/summary] - -Check it on the demo below. **When you press `run`, the browser may halt for some time**, because it changes `div.style.backgroundColor` from #A00000 to #FFFFFF. - -In most browsers, you see nothing until the script finishes, or until the browser pauses it with a message that 'a script is running too long'. - -The exception is Opera. - -[html run] -
- - - - -[/html] - -In Opera, you may notice `div` is redrawn. Not every change causes a repaint, probably because of Opera internal scheduling. That's because event queues for rendering and JavaScript are different in this browser. - -In other browsers the repaint is postponed until the JavaScript finishes. - -Again, the implementation may be different, but generally **the nodes are marked as "dirty" (want to be recalculated and redrawn), and repaint is queued**. Or, the browser may just look for dirty nodes after every script and process them. - -[smart header="Immediate reflow"] -The browser contains many optimizations to speedup rendering and painting. Generally, it tries to postpone them until the script is finished, but some actions require nodes to be rerendered immediately. - -For example: -[js] -elem.innerHTML = 'new content' -alert(elem.offsetHeight) // <-- rerenders elem to get offsetHeight -[/js] - -In the case above, the browser has to perform relayouting to get the height. -But it doesn't have to repaint `elem` on the screen. - -Sometimes other dependant nodes may get involved into calculations. This process is called *reflow* and may consume lots of resources if script causes it often. - -Surely, there's much more to talk about rendering. It will be covered by a separate article [todo]. -[/smart] - - -## Modal and synchronous calls - -[summary]Modal and synchronous calls like `alert` pause the JavaScript thread. - -That causes related activities to freeze. -[/summary] - -The example below demonstrates it. - -
    -
  1. Press "Run". The `setInterval`-based animation will start and and `alert` button will appear.
  2. -
  3. Press the button, note that the animation stops.
  4. -
- - -[html run height=60] -
- - - -[/html] - -When you press `alert('Hello!')`, the `alert` blocks JavaScript execution and blocks the whole UI thread. That's how `alert`, `confirm` and `prompt` work. And there is only one thread. So, **`setTimeout/setInterval` can't execute while the thread is blocked.** - - -### Opera: `iframes` exception. - -[summary]Usually, `iframes` run in the same thread with the page. [/summary] - -But there is an exception called Opera. **Run the example above in Opera** and press alert in the main window. The iframe animation will continue! -That's because the example is actually running in an iframe. - -Other browsers use single thread for whole tab, so the iframe animation is paused there. - - - -## Script taking too long and heavy jobs - -JavaScript can be heavy. - -In this case, the browser may hangup for a moment or come with a warning "Script is taking too long". - -We'd want to evade that. It can be done by split the job into parts which get scheduled after each other. - -Then there is a "free time" for the browser to respond between parts. It is can render and react on other events. Both the visitor and the browser are happy. - -The background color in the example below is changed once per tick. So the browser has the time to render it, and there are no hangups. Changes are applied incrementally. - -Press the run button on the example to start. -[html run] -
- - - - - -[/html] - -The internal order: -
    -
  1. `setTimeout` appends the `func` call to the event queue.
  2. -
  3. The new call is scheduled on the next tick.
  4. -
  5. The func executes and changes the `div` which appends a repaint request to the queue.
  6. -
  7. The function finishes. The browser takes the next event from the queue which is repaint and executes it. Then it waits the next tick to execute one more `func` call (see step 2).
  8. -
  9. Repeated until `stop()`
  10. -
- -A delay may be increased from 0 to 100 ms, depending on your needs. The longer delay leads to less CPU load. - -[smart header="Evade the 'script is running for too long' warning"] -As an important side-effect, splitting the long job into parts which are executed by `setTimeout` helps to fix browser hangups and evade warnings. - -For example, modern syntax highlighters employ such technique. When a visitor opens a large text, they highlight a part of it then call something like `setTimeout(highlightNext, 50)` which highlights the next part etc. - -It would hangup otherwise, because the syntax highlighting takes time. -[/smart] - - - -## Summary - -Most browsers use single thread for UI and JavaScript, which is blocked by synchronous calls. So, JavaScript execution blocks the rendering. - -Events are processed asynchronously with the exception of DOM events. - -The `setTimeout(..,0)` trick is very useful. It allows to: - - -Opera is special in many places when it comes to timeouts and threading. diff --git a/archive/2-eval-calculator-errors/solution.md b/archive/2-eval-calculator-errors/solution.md deleted file mode 100644 index c564d3ee..00000000 --- a/archive/2-eval-calculator-errors/solution.md +++ /dev/null @@ -1,34 +0,0 @@ -Вычислить любое выражение нам поможет `eval`: - -```js run -alert( eval("2+2") ); // 4 -``` - -Считываем выражение в цикле `while(true)`. Если при вычислении возникает ошибка -- ловим её в `try..catch`. - -Ошибкой считается, в том числе, получение `NaN` из `eval`, хотя при этом исключение не возникает. Можно бросить своё исключение в этом случае. - -Код решения: - -```js run demo -let expr, res; - -while (true) { - expr = prompt("Введите выражение?", '2-'); - if (expr == null) break; - - try { - res = eval(expr); - if (isNaN(res)) { - throw new Error("Результат неопределён"); - } - - break; - } catch (e) { - alert( "Ошибка: " + e.message + ", повторите ввод" ); - } -} - -alert( res ); -``` - diff --git a/archive/2-eval-calculator-errors/task.md b/archive/2-eval-calculator-errors/task.md deleted file mode 100644 index b317d52e..00000000 --- a/archive/2-eval-calculator-errors/task.md +++ /dev/null @@ -1,14 +0,0 @@ -importance: 5 - ---- - -# Eval-калькулятор с ошибками [todo: NO EVAL YET] - -Напишите интерфейс, который принимает математическое выражение (в `prompt`) и результат его вычисления через `eval`. - -**При ошибке нужно выводить сообщение и просить переввести выражение**. - -Ошибкой считается не только некорректное выражение, такое как `2+`, но и выражение, возвращающее `NaN`, например `0/0`. - -[demo] - diff --git a/archive/2-events-and-timing-depth/article.md b/archive/2-events-and-timing-depth/article.md deleted file mode 100644 index 3254326f..00000000 --- a/archive/2-events-and-timing-depth/article.md +++ /dev/null @@ -1,170 +0,0 @@ -# Порядок обработки событий - -События могут возникать не только по очереди, но и "пачкой" по много сразу. Возможно и такое, что во время обработки одного события возникают другие, например пока выполнялся код для `onclick` -- посетитель нажал кнопку на клавиатуре (событие `keydown`). - -Здесь мы разберём, как браузер обычно работает с одновременно возникающими событиями и какие есть исключения из общего правила. - -## Главный поток - -В каждом окне выполняется только один *главный* поток, который занимается выполнением JavaScript, отрисовкой и работой с DOM. - -Он выполняет команды последовательно, может делать только одно дело одновременно и блокируется при выводе модальных окон, таких как `alert`. - -```smart header="Дополнительные потоки тоже есть" -Есть и другие, служебные потоки, например, для сетевых коммуникаций. - -Поэтому скачивание файлов может продолжаться пока главный поток ждёт реакции на `alert`. Но управлять служебными потоками мы не можем. -``` - -```smart header="Web Workers" -Существует спецификация Web Workers, которая позволяет запускать дополнительные JavaScript-процессы(workers). - -Они могут обмениваться сообщениями с главным процессом, но у них свои переменные, и работают они также сами по себе. - -Такие дополнительные процессы не имеют доступа к DOM, поэтому они полезны, преимущественно, при вычислениях, чтобы загрузить несколько ядер/процессоров одновременно. -``` - -## Очередь событий - -Произошло одновременно несколько событий или во время работы одного случилось другое -- как главному потоку обработать это? - -Если главный поток прямо сейчас занят, то он не может срочно выйти из середины одной функции и прыгнуть в другую. А потом третью. Отладка при этом могла бы превратиться в кошмар, потому что пришлось бы разбираться с совместным состоянием нескольких функций сразу. - -Поэтому используется альтернативный подход. - -**Когда происходит событие, оно попадает в очередь.** - -Внутри браузера непрерывно работает "главный внутренний цикл", который следит за состоянием очереди и обрабатывает события, запускает соответствующие обработчики и т.п. - -**Иногда события добавляются в очередь сразу пачкой.** - -Например, при клике на элементе генерируется несколько событий: - -1. Сначала `mousedown` -- нажата кнопка мыши. -2. Затем `mouseup` -- кнопка мыши отпущена и, так как это было над одним элементом, то дополнительно генерируется `click` (два события сразу). - -````online -В действии: - -```html autorun height=150 no-beautify - - - -``` -```` - -Таким образом, при нажатии кнопки мыши в очередь попадёт событие `mousedown`, а при отпускании -- сразу два события: `mouseup` и `click`. Браузер обработает их строго одно за другим: `mousedown` -> `mouseup` -> `click`. - -При этом каждое событие из очереди обрабатывается полностью отдельно от других. - -## Вложенные (синхронные) события - -Обычно возникающие события "становятся в очередь". - -Но в тех случаях, когда событие инициируется не посетителем, а кодом, то оно, как правило, обрабатывается синхронно, то есть прямо сейчас. - -Рассмотрим в качестве примера событие `onfocus`. - -### Пример: событие onfocus - -Когда посетитель фокусируется на элементе, возникает событие `onfocus`. Обычно оно происходит, когда посетитель кликает на поле ввода, например: - -```html run height=80 autorun -

При фокусе на поле оно изменит значение.

- -``` - -Но ту же фокусировку можно вызвать и явно, вызовом метода `elem.focus()`: - -```html run - - - -``` - -В главе мы познакомимся с этим событием подробнее, а пока -- нажмите на кнопку в примере ниже. - -При этом обработчик `onclick` вызовет метод `focus()` на текстовом поле `text`. Код обработчика `onfocus`, который при этом запустится, сработает синхронно, прямо сейчас, до завершения `onclick`. - -```html autorun height=80 no-beautify - - - - -``` - -При клике на кнопке в примере выше будет видно, что управление вошло в `onclick`, затем перешло в `onfocus`, затем вышло из `onclick`. - -```warn header="Исключение в IE" -Так ведут себя все браузеры, кроме IE. - -В нём событие `onfocus` -- всегда асинхронное, так что будет сначала полностью обработан клик, а потом -- фокус. В остальных -- фокус вызовется посередине клика. Попробуйте кликнуть в IE и в другом браузере, чтобы увидеть разницу. -``` - -## Делаем события асинхронными через setTimeout(...,0) - -А что, если мы хотим, чтобы *сначала* закончилась обработка `onclick`, а потом уже произошла обработка `onfocus` и связанные с ней действия? - -Можно добиться и этого. - -Один вариант -- просто переместить строку `text.focus()` вниз кода обработчика `onclick`. - -Если это неудобно, можно запланировать `text.focus()` чуть позже через `setTimeout(..., 0)`, вот так - -```html autorun height=80 - - - - -``` - -Такой вызов обеспечит фокусировку через минимальный "тик" таймера, по стандарту равный 4 мс. Обычно такая задержка не играет роли, а необходимую асинхронность мы получили. - -## Итого - -- JavaScript выполняется в едином потоке. Современные браузеры позволяют порождать подпроцессы Web Workers, они выполняются параллельно и могут отправлять/принимать сообщения, но не имеют доступа к DOM. -- Обычно события становятся в очередь и обрабатываются в порядке поступления, асинхронно, независимо друг от друга. -- Синхронными являются вложенные события, инициированные из кода. -- Чтобы сделать событие гарантированно асинхронным, используется вызов через `setTimeout(func, 0)`. - -Отложенный вызов через `setTimeout(func, 0)` используется не только в событиях, а вообще -- всегда, когда мы хотим, чтобы некая функция `func` сработала после того, как текущий скрипт завершится. - diff --git a/archive/4-random-from-array/solution.md b/archive/4-random-from-array/solution.md deleted file mode 100644 index c07a93bc..00000000 --- a/archive/4-random-from-array/solution.md +++ /dev/null @@ -1,12 +0,0 @@ -We need to generate a random integer value from `0` to `arr.length-1`, and then take the element with that index. - -Here we go: - -```js run -let arr = ["Apple", "Orange", "Pear", "Lemon"]; - -let rand = Math.floor(Math.random() * arr.length); - -alert( arr[rand] ); -``` - diff --git a/archive/4-random-from-array/task.md b/archive/4-random-from-array/task.md deleted file mode 100644 index c40a10c1..00000000 --- a/archive/4-random-from-array/task.md +++ /dev/null @@ -1,11 +0,0 @@ -importance: 3 - ---- - -# A random array value - -Write the code to `alert` a random value from the array: - -```js -let arr = ["Apple", "Orange", "Pear", "Lemon"]; -``` diff --git a/archive/5-drag-and-drop-objects/article.md b/archive/5-drag-and-drop-objects/article.md deleted file mode 100644 index 3b8f3313..00000000 --- a/archive/5-drag-and-drop-objects/article.md +++ /dev/null @@ -1,512 +0,0 @@ -# Мышь: Drag'n'Drop более глубоко - -В [предыдущей статье](/drag-and-drop) мы рассмотрели основы Drag'n'Drop. Здесь мы разберём дополнительные "тонкие места" и приёмы реализации, которые возникают на практике. - -Почти все javascript-библиотеки реализуют Drag'n'Drop так, как написано (хотя бывает что и менее эффективно). - -Зная, что и как, вы сможете легко написать свой код переноса или поправить, адаптировать существующую библиотеку под себя. - -Этот материал не строго обязателен для изучения, он специфичен именно для Drag'n'Drop. - -## Документ - -Как пример задачи -- возьмём документ с иконками браузера ("объекты переноса"), которые можно переносить в компьютер ("цель переноса"): - -- Элементы, которые можно переносить (иконки браузеров), помечены классом `draggable`. -- Элементы, на которые можно положить (компьютер), имеют класс `droppable`. - -```html - - - - - - -

Браузер переносить сюда:

- - -``` - -Работающий пример с переносом: - -[iframe border=1 src="dragDemo" height=280 link edit] - -Далее мы рассмотрим, как делается фреймворк для таких переносов, а в перспективе -- и для более сложных. - -Требования: - -- Поддержка большого количества элементов без "тормозов". -- Продвинутые возможности по анимации переноса. -- Удобная обработка успешного и неудачного переноса. - -## Начало переноса - -Чтобы начать перенос элемента, мы должны отловить нажатие левой кнопки мыши на нём. Для этого используем событие `mousedown`... И, конечно, делегирование. - -Переносимых элементов может быть много. В нашем документе-примере это всего лишь несколько иконок, но если мы хотим переносить элементы списка или дерева, то их может быть 100 штук и более. - -Поэтому повесим обработчик `mousedown` на контейнер, который содержит переносимые элементы, и будем определять нужный элемент поиском ближайшего `draggable` вверх по иерархии от `event.target`. - -В качестве контейнера здесь будем брать `document`, хотя это может быть и любой элемент. - -Найденный `draggable`-элемент сохраним в свойстве `dragObject.elem` и начнём двигать. - -Код обработчика `mousedown`: - -```js -let dragObject = {}; - -document.onmousedown = function(e) { - - if (e.which != 1) { // если клик правой кнопкой мыши - return; // то он не запускает перенос - } - - let elem = e.target.closest('.draggable'); - - if (!elem) return; // не нашли, клик вне draggable-объекта - - // запомнить переносимый объект - dragObject.elem = elem; - - // запомнить координаты, с которых начат перенос объекта - dragObject.downX = e.pageX; - dragObject.downY = e.pageY; -} -``` - -```warn header="Не начинаем перенос по `mousedown`" -Ранее мы по `mousedown` начинали перенос. - -Но на самом деле нажатие на элемент вовсе не означает, что его собираются куда-то двигать. Возможно, на нём просто кликают. - -Это важное различие. Снимать элемент со своего места и куда-то двигать нужно только при переносе. - -Чтобы отличить перенос от клика, в том числе -- от клика, который сопровождается нечаянным перемещением на пару пикселей (рука дрогнула), мы будем запоминать в `dragObject`, какой элемент (`elem`) и где (`downX/downY`) был зажат, а начало переноса будем инициировать из `mousemove`, если он передвинут хотя бы на несколько пикселей. -``` - -## Перенос элемента - -Первой задачей обработчика `mousemove` является инициировать начало переноса, если элемент передвинули в зажатом состоянии. - -Ну а второй задачей -- отображать его перенос при каждом передвижении мыши. - -Схематично, обработчик будет иметь такой вид: - -```js -document.onmousemove = function(e) { - if (!dragObject.elem) return; // элемент не зажат - - if (!dragObject.avatar) { // элемент нажат, но пока не начали его двигать - ...начать перенос, присвоить dragObject.avatar = переносимый элемент - } - - ...отобразить перенос элемента... -} -``` - -Здесь мы видим новое свойство `dragObject.avatar`. При начале переноса "аватар" делается из элемента и сохраняется в свойство `dragObject.avatar`. - -**"Аватар" -- это DOM-элемент, который перемещается по экрану.** - -Почему бы не перемещать по экрану сам `draggable`-элемент? Зачем, вообще, нужен аватар? - -Дело в том, что иногда сам элемент передвигать неудобно, например потому, что он слишком большой. А удобно создать некоторое визуальное представление элемента, и его уже переносить. Аватар дает такую возможность. - -А в простейшем случае аватаром можно будет сделать сам элемент, и это не повлечёт дополнительных расходов. - -### Визуальное перемещение аватара - -Для того, чтобы отобразить перенос аватара, достаточно поставить ему `position: absolute` и менять координаты `left/top`. - -Для использования абсолютных координат относительно документа, аватар должен быть прямым потомком `BODY`. - -Следующий код готовит аватар к переносу: - -```js -// в начале переноса: -if (avatar.parentNode != document.body) { - document.body.appendChild(avatar); // переместить в BODY, если надо -} -avatar.style.zIndex = 9999; // сделать, чтобы элемент был над другими -avatar.style.position = 'absolute'; -``` - -... А затем его можно двигать: - -```js -// при каждом движении мыши - -avatar.style.left = новая координата + 'px'; -avatar.style.top = новая координата + 'px'; -``` - -Как вычислять новые координаты `left/top` при переносе? - -Чтобы элемент сохранял свою позицию под курсором, необходимо при нажатии запомнить его изначальный сдвиг относительно курсора, и сохранять его при переносе. - -![](shiftx.png) - -Этот сдвиг по горизонтали обозначен `shiftX` на рисунке выше. Аналогично, есть `shiftY`. Они вычисляются как расстояние между курсором и левой/верхней границей элемента при `mousedown`. Детали вычислений описаны в главе . - -Таким образом, при `mousemove` мы будем назначать элементу координаты курсора с учетом сдвига `shiftX/shiftY`: - -```js -avatar.style.left = e.pageX - shiftX + 'px'; -avatar.style.top = e.pageY - shiftY + 'px'; -``` - -## Полный код mousemove - -Код `mousemove`, решающий задачу начала переноса и позиционирования аватара: - -```js -document.onmousemove = function(e) { - if (!dragObject.elem) return; // элемент не зажат - - if ( !dragObject.avatar ) { // если перенос не начат... - - // посчитать дистанцию, на которую переместился курсор мыши - let moveX = e.pageX - dragObject.downX; - let moveY = e.pageY - dragObject.downY; - if ( Math.abs(moveX) < 3 && Math.abs(moveY) < 3 ) { - return; // ничего не делать, мышь не передвинулась достаточно далеко - } - - *!*dragObject.avatar = createAvatar(e)*/!*; // захватить элемент - if (!dragObject.avatar) { - dragObject = {}; // аватар создать не удалось, отмена переноса - return; // возможно, нельзя захватить за эту часть элемента - } - - // аватар создан успешно - // создать вспомогательные свойства shiftX/shiftY - let coords = getCoords(dragObject.avatar); - dragObject.shiftX = dragObject.downX - coords.left; - dragObject.shiftY = dragObject.downY - coords.top; - - *!*startDrag(e)*/!*; // отобразить начало переноса - } - - // отобразить перенос объекта при каждом движении мыши - dragObject.avatar.style.left = e.pageX - dragObject.shiftX + 'px'; - dragObject.avatar.style.top = e.pageY - dragObject.shiftY + 'px'; - - return false; -} -``` - -Здесь используются две функции для начала переноса: `createAvatar(e)` и `startDrag(e)`. - -Функция `createAvatar(e)` создает аватар. В нашем случае в качестве аватара берется сам `draggable` элемент. После создания аватара в него записывается функция `avatar.rollback`, которая задает поведение при отмене переноса. - -Как правило, отмена переноса влечет за собой разрушение аватара, если это был клон, или возвращение его на прежнее место, если это сам элемент. - -В нашем случае для отмены переноса нужно запомнить старую позицию элемента и его родителя. - -```js -function createAvatar(e) { - - // запомнить старые свойства, чтобы вернуться к ним при отмене переноса - let avatar = dragObject.elem; - let old = { - parent: avatar.parentNode, - nextSibling: avatar.nextSibling, - position: avatar.position || '', - left: avatar.left || '', - top: avatar.top || '', - zIndex: avatar.zIndex || '' - }; - - // функция для отмены переноса - avatar.rollback = function() { - old.parent.insertBefore(avatar, old.nextSibling); - avatar.style.position = old.position; - avatar.style.left = old.left; - avatar.style.top = old.top; - avatar.style.zIndex = old.zIndex - }; - - return avatar; -} -``` - -Функция `startDrag(e)`, которую вызывает `mousemove`, если видит, что элемент в "зажатом" состоянии перенесли достаточно далеко, инициирует начало переноса и позиционирует аватар на странице: - -```js -function startDrag(e) { - let avatar = dragObject.avatar; - - document.body.appendChild(avatar); - avatar.style.zIndex = 9999; - avatar.style.position = 'absolute'; -} -``` - -## Окончание переноса - -Окончание переноса происходит по событию `mouseup`. - -Его обработчик можно поставить на аватаре, т.к. аватар всегда под курсором и `mouseup` происходит на нем. Но для универсальности и большей гибкости (вдруг мы захотим перемещать аватар *рядом* с курсором?) поставим его, как и остальные, на `document`. - -Задача обработчика `mouseup`: - -1. Обработать успешный перенос, если он идет (существует аватар) -2. Очистить данные `dragObject`. - -Это дает нам следующий код: - -```js -document.onmouseup = function(e) { - // (1) обработать перенос, если он идет - if (dragObject.avatar) { - *!*finishDrag(e)*/!*; - } - - // в конце mouseup перенос либо завершился, либо даже не начинался - // (2) в любом случае очистим "состояние переноса" dragObject - dragObject = {}; -} -``` - -Для завершения переноса в функции `finishDrag(e)` нам нужно понять, на каком элементе мы находимся, и если над `droppable` -- обработать перенос, а нет -- откатиться: - -```js -function finishDrag(e) { - let dropElem = *!*findDroppable(e)*/!*; - - if (dropElem) { - ... успешный перенос ... - } else { - ... отмена переноса ... - } -} -``` - -### Определяем элемент под курсором - -Чтобы понять, над каким элементом мы остановились -- используем метод [document.elementFromPoint(clientX, clientY)](https://developer.mozilla.org/en/DOM/document.elementFromPoint), который мы обсуждали в разделе [координаты](info:coordinates#elementFromPoint). Этот метод получает координаты *относительно окна* и возвращает самый глубокий элемент, который там находится. - -Функция `findDroppable(event)`, описанная ниже, использует его и находит самый глубокий элемент с атрибутом `droppable` под курсором мыши: - -```js -// возвратит ближайший droppable или null -*!* -// это предварительный вариант findDroppable, исправлен ниже! -*/!* -function findDroppable(event) { - - // взять элемент на данных координатах - let elem = document.elementFromPoint(event.clientX, event.clientY); - - // найти ближайший сверху droppable - return elem.closest('.droppable'); -} -``` - -Обратите внимание -- для `elementFromPoint` нужны координаты относительно окна `clientX/clientY`, а не `pageX/pageY`. - -Вариант выше -- предварительный. Он не будет работать. Если попробовать применить эту функцию, будет все время возвращать один и тот же элемент! А именно -- *текущий переносимый*. Почему так? - -...Дело в том, что в процессе переноса под мышкой находится именно аватар. При начале переноса ему даже `z-index` ставится большой, чтобы он был поверх всех остальных. - -**Аватар перекрывает остальные элементы. Поэтому функция `document.elementFromPoint()` увидит на текущих координатах именно его.** - -Чтобы это изменить, нужно либо поправить код переноса, чтобы аватар двигался *рядом* с курсором мыши, либо дать аватару стиль `pointer-events:none` (кроме IE10-), либо: - -1. Спрятать аватар. -2. Вызывать `elementFromPoint`. -3. Показать аватар. - -Напишем функцию `findDroppable(event)`, которая это делает: - -```js -function findDroppable(event) { - // спрячем переносимый элемент - dragObject.avatar.hidden = true; - - // получить самый вложенный элемент под курсором мыши - let elem = document.elementFromPoint(event.clientX, event.clientY); - - // показать переносимый элемент обратно - dragObject.avatar.hidden = false; - - if (elem == null) { - // такое возможно, если курсор мыши "вылетел" за границу окна - return null; - } - - return elem.closest('.droppable'); -} -``` - -## DragManager - -Из фрагментов кода, разобранных выше, можно собрать мини-фреймворк. - -Объект `DragManager` будет запоминать текущий переносимый объект и отслеживать его перенос. - -Для его создания используем не обычный синтаксис `{...}`, а вызов `new function`. Это позволит прямо при создании объявить дополнительные переменные и функции в замыкании, которыми могут пользоваться методы объекта, а также назначить обработчики: - -```js no-beautify -let DragManager = new function() { - - let dragObject = {}; - - let self = this; // для доступа к себе из обработчиков - - function onMouseDown(e) { ... } - function onMouseMove(e) { ... } - function onMouseUp(e) { ... } - - document.onmousedown = onMouseDown; - document.onmousemove = onMouseMove; - document.onmouseup = onMouseUp; - - this.onDragEnd = function(dragObject, dropElem) { }; - this.onDragCancel = function(dragObject) { }; -} -``` - -Всю работу будут выполнять обработчики `onMouse*`, которые оформлены как локальные функции. В данном случае они ставятся на `document` через `on...`, но это легко поменять на `addEventListener`. - -Код функции `onMouse*` мы подробно рассмотрели ранее, но вы сможете увидеть их в полном примере ниже. - -Внутренний объект `dragObject` будет содержать информацию об объекте переноса. - -У него будут следующие свойства, которые также разобраны выше: - -`elem` -: Текущий зажатый мышью объект, если есть (ставится в `mousedown`). - -`avatar` -: Элемент-аватар, который передвигается по странице. - -`downX/downY` -: Координаты, на которых был клик `mousedown` - -`shiftX/shiftY` -: Относительный сдвиг курсора от угла элемента, вспомогательное свойство вычисляется в начале переноса. - -Задачей `DragManager` является общее управление переносом. Что же касается действий при его окончании -- их должен назначить внешний код, который использует `DragManager`. - -Можно сделать это через вспомогательные методы `onDrag*`, которые устанавливаются внешним кодом и затем вызываются фреймворком. Разработчик, подключив `DragManager`, описывает в этих методах, что делать при завершении или отмене переноса. Конечно же, можно заменить методы `onDrag*` на генерацию "своих" событий. - -С использованием `DragManager` пример, с которого начиналась эта глава -- перенос иконок браузеров в компьютер, реализуется совсем просто: - -```js no-beautify -DragManager.onDragEnd = function(dragObject, dropElem) { - - // скрыть/удалить переносимый объект - dragObject.elem.hidden = true; - - // успешный перенос, показать улыбку классом computer-smile - dropElem.className = 'computer computer-smile'; - - // убрать улыбку через 0.2 сек - setTimeout(function() { - dropElem.classList.remove('computer-smile'); - }, 200); -}; - -DragManager.onDragCancel = function(dragObject) { - // откат переноса - dragObject.avatar.rollback(); -}; -``` - -Полный пример с кодом: - -[codetabs src="dragDemo" height=280] - -## Расширения - -Существует масса возможных применений Drag'n'Drop. Здесь мы не будем реализовывать их все, поскольку не стоит цель создать фреймворк-монстр. - -Однако, мы рассмотрим их, чтобы, при необходимости, легко было написать то, что нужно. - -### Захватывать элемент можно только за "ручку" - -Часто бывает, что перенос должен быть инициирован только при захвате за определённую зону элемента. К примеру, модальное окно можно "взять", только захватив его за заголовок. - -Для этого достаточно добавить необходимую проверку, к примеру, в функцию `createAvatar` или перед её запуском. - -Если `mousedown` был внутри элемента, помеченного, к примеру, классом `draghandle`, то начинаем перенос, иначе -- нет. - -### Проверка прав на droppable - -Бывает и так, что не на любое место в `droppable` можно положить элемент. - -Например: в админке есть дерево всех объектов сайта: статей, разделов, посетителей и т.п. - -- В этом дереве есть узлы различных типов: "статьи", "разделы" и "пользователи". -- Все узлы являются переносимыми объектами. -- Узел "статья" (draggable) можно переносить в "раздел" (droppable), а узел "пользователи" -- нельзя. Но и то и другое можно поместить в "корзину". - -Здесь решение: "можно или нет" переносить или нельзя зависит от "типа" переносимого объекта. - -Есть и более сложные варианты, когда решение зависит от конкретного места в `droppable`, над которым посетитель отпустил кнопку мыши. К примеру, переносить в верхнюю часть можно, а в нижнюю -- нет. - -Эта задача решается добавлением проверки в `findDroppable(e)`. Эта функция знает и об аватаре и о событии, включая координаты. При попытке положить в "неправильное" место функция `findDroppable(e)` должна возвращать `null`. - -Однако, на практике бывают ситуации, когда решение "прямо сейчас" принять невозможно. Например, нужно сделать запрос на сервер: "А разрешено ли текущему посетителю производить такую операцию?" - -Как при этом должен вести себя интерфейс? Можно, конечно сделать, чтобы элемент после отпускания кнопки мыши "завис" над `droppable`, ожидая ответа. Однако, такое решение неудобно в реализации и странновато выглядит для посетителя. - -Как правило, применяют "оптимистичный" алгоритм, по которому мы считаем, что перенос обычно успешен, но при необходимости можем отменить его. - -При нём посетитель кладет объект туда, куда он хочет, а затем, в коде `onDragEnd`: - -1. Визуально обрабатывается завершение переноса, как будто все ок. -2. Производится асинхронный запрос к серверу, содержащий информацию о переносе. -3. Сервер обрабатывает перенос и возвращает ответ, все ли в порядке. -4. Если нет -- выводится ошибка и возвращается `avatar.rollback()`. Аватар в этом случае должен предусматривать возможность отката после успешного завершения. - -Процесс общения с сервером сопровождается индикацией загрузки и, при необходимости, блокировкой новых операций переноса до получения подтверждения. - -### Подсветка текущего droppable - -Удобно, когда пользователь во время переноса наглядно видит, куда он сейчас положит draggable. Например, текущий droppable (или его часть) подсвечиваются. - -Для этого в `DragManager` можно добавить дополнительные методы интеграции с внешним кодом: - -- `onDragEnter` -- будет вызываться при заходе на `droppable`, из `onMouseMove`. -- `onDragMove` -- при каждом передвижении внутри `droppable`, из `onMouseMove`. -- `onDragLeave` -- при выходе с `droppable`, из `onMouseMove` и `onMouseUp`. - -Возможен более сложный вариант, когда нужно поддерживать не только перенос *в элемент*, но и перенос *между элементами*, например вставку одной статьи между двумя другими. - -Для этого код, который обрабатывает перенос, может "делить на части" droppable, к примеру, в отношении 25% - 50% - 25%, и смотреть: - -- Если перенос в верхнюю четверть, то это -- "над". -- Если перенос в середину, то это "внутрь". -- Если перенос в нижнюю четверть, то это -- "под". - -Текущий `droppable` и позиция относительно него при этом могут помечаться подсветкой и жирной чертой над/под, если требуется. - -Пример индикации из Firefox: -![](between.png) - -### Анимация отмены переноса - -Отмену переноса и возврат аватара на место можно красиво анимировать. - -Один из частых вариантов -- скольжение объекта обратно к исходному месту, откуда его взяли. Для этого достаточно поправить `avatar.rollback()`. - -## Итого - -Уточнённый алгоритм Drag'n'Drop: - -1. При `mousedown` запомнить координаты нажатия. -2. При `mousemove` инициировать перенос, как только зажатый элемент передвинули на 3 пикселя или больше. Сообщить во внешний код вызовом `onDragStart`. При этом: -
    -3. Создать аватар, если можно начать перенос элемента `draggable` с данной позиции курсора. -4. Переместить аватар по экрану, установив его новую позицию из `e.pageX/pageY` с учетом изначального сдвига элемента относительно курсора. -5. Сообщить во внешний код о текущем `droppable` под курсором и позиции над ним вызовами `onDragEnter`, `onDragMove`, `onDragLeave`. -6. При `mouseup` обработать завершение переноса. Элемент под аватаром получить по координатам, предварительно спрятав аватар. Сообщить во внешний код вызовом `onDragEnd`. - -Получившаяся реализация Drag'n'Drop проста, эффективна, изящна. - -Её очень легко поменять или адаптировать под "особые" потребности. - -ООП-вариант фреймворка находится в статье . diff --git a/archive/5-drag-and-drop-objects/between.png b/archive/5-drag-and-drop-objects/between.png deleted file mode 100644 index 4001dff0..00000000 Binary files a/archive/5-drag-and-drop-objects/between.png and /dev/null differ diff --git a/archive/5-drag-and-drop-objects/dragDemo.view/DragManager.js b/archive/5-drag-and-drop-objects/dragDemo.view/DragManager.js deleted file mode 100644 index 24a208db..00000000 --- a/archive/5-drag-and-drop-objects/dragDemo.view/DragManager.js +++ /dev/null @@ -1,157 +0,0 @@ -let DragManager = new function() { - - /** - * составной объект для хранения информации о переносе: - * { - * elem - элемент, на котором была зажата мышь - * avatar - аватар - * downX/downY - координаты, на которых был mousedown - * shiftX/shiftY - относительный сдвиг курсора от угла элемента - * } - */ - let dragObject = {}; - - let self = this; - - function onMouseDown(e) { - - if (e.which != 1) return; - - let elem = e.target.closest('.draggable'); - if (!elem) return; - - dragObject.elem = elem; - - // запомним, что элемент нажат на текущих координатах pageX/pageY - dragObject.downX = e.pageX; - dragObject.downY = e.pageY; - - return false; - } - - function onMouseMove(e) { - if (!dragObject.elem) return; // элемент не зажат - - if (!dragObject.avatar) { // если перенос не начат... - let moveX = e.pageX - dragObject.downX; - let moveY = e.pageY - dragObject.downY; - - // если мышь передвинулась в нажатом состоянии недостаточно далеко - if (Math.abs(moveX) < 3 && Math.abs(moveY) < 3) { - return; - } - - // начинаем перенос - dragObject.avatar = createAvatar(e); // создать аватар - if (!dragObject.avatar) { // отмена переноса, нельзя "захватить" за эту часть элемента - dragObject = {}; - return; - } - - // аватар создан успешно - // создать вспомогательные свойства shiftX/shiftY - let coords = getCoords(dragObject.avatar); - dragObject.shiftX = dragObject.downX - coords.left; - dragObject.shiftY = dragObject.downY - coords.top; - - startDrag(e); // отобразить начало переноса - } - - // отобразить перенос объекта при каждом движении мыши - dragObject.avatar.style.left = e.pageX - dragObject.shiftX + 'px'; - dragObject.avatar.style.top = e.pageY - dragObject.shiftY + 'px'; - - return false; - } - - function onMouseUp(e) { - if (dragObject.avatar) { // если перенос идет - finishDrag(e); - } - - // перенос либо не начинался, либо завершился - // в любом случае очистим "состояние переноса" dragObject - dragObject = {}; - } - - function finishDrag(e) { - let dropElem = findDroppable(e); - - if (!dropElem) { - self.onDragCancel(dragObject); - } else { - self.onDragEnd(dragObject, dropElem); - } - } - - function createAvatar(e) { - - // запомнить старые свойства, чтобы вернуться к ним при отмене переноса - let avatar = dragObject.elem; - let old = { - parent: avatar.parentNode, - nextSibling: avatar.nextSibling, - position: avatar.position || '', - left: avatar.left || '', - top: avatar.top || '', - zIndex: avatar.zIndex || '' - }; - - // функция для отмены переноса - avatar.rollback = function() { - old.parent.insertBefore(avatar, old.nextSibling); - avatar.style.position = old.position; - avatar.style.left = old.left; - avatar.style.top = old.top; - avatar.style.zIndex = old.zIndex - }; - - return avatar; - } - - function startDrag(e) { - let avatar = dragObject.avatar; - - // инициировать начало переноса - document.body.appendChild(avatar); - avatar.style.zIndex = 9999; - avatar.style.position = 'absolute'; - } - - function findDroppable(event) { - // спрячем переносимый элемент - dragObject.avatar.hidden = true; - - // получить самый вложенный элемент под курсором мыши - let elem = document.elementFromPoint(event.clientX, event.clientY); - - // показать переносимый элемент обратно - dragObject.avatar.hidden = false; - - if (elem == null) { - // такое возможно, если курсор мыши "вылетел" за границу окна - return null; - } - - return elem.closest('.droppable'); - } - - document.onmousemove = onMouseMove; - document.onmouseup = onMouseUp; - document.onmousedown = onMouseDown; - - this.onDragEnd = function(dragObject, dropElem) {}; - this.onDragCancel = function(dragObject) {}; - -}; - - -function getCoords(elem) { // кроме IE8- - let box = elem.getBoundingClientRect(); - - return { - top: box.top + pageYOffset, - left: box.left + pageXOffset - }; - -} \ No newline at end of file diff --git a/archive/5-drag-and-drop-objects/dragDemo.view/dragDemo.css b/archive/5-drag-and-drop-objects/dragDemo.view/dragDemo.css deleted file mode 100644 index d9cf2ac6..00000000 --- a/archive/5-drag-and-drop-objects/dragDemo.view/dragDemo.css +++ /dev/null @@ -1,15 +0,0 @@ -.computer { - width: 93px; - height: 98px; - background: url(https://js.cx/clipart/computer.gif) no-repeat; - padding: 5px; - font-style: italic; -} - -.computer-smile { - background: url(https://js.cx/clipart/computer-smile.gif) no-repeat; -} - -.draggable { - cursor: pointer; -} \ No newline at end of file diff --git a/archive/5-drag-and-drop-objects/dragDemo.view/index.html b/archive/5-drag-and-drop-objects/dragDemo.view/index.html deleted file mode 100644 index cb4fc01b..00000000 --- a/archive/5-drag-and-drop-objects/dragDemo.view/index.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - -
    - - - - - -
    - -

    Браузер переносить сюда:

    - -
    -
    - - - - \ No newline at end of file diff --git a/archive/5-drag-and-drop-objects/shiftx.png b/archive/5-drag-and-drop-objects/shiftx.png deleted file mode 100644 index 52d49dd4..00000000 Binary files a/archive/5-drag-and-drop-objects/shiftx.png and /dev/null differ diff --git a/archive/backticks.md b/archive/backticks.md deleted file mode 100644 index 1f1dd5cd..00000000 --- a/archive/backticks.md +++ /dev/null @@ -1,51 +0,0 @@ - -Backticks allow to specify a "template function" before the first backtick. - -The syntax is: -```js -let str = func`my string`; -``` - -The function `func` is automatically called and receives the array of string pieces split by `${...}` embeds and the list of embedded `${...}` values. - -It's better to see the example: - -```js run -function love(s, v1, v2) { - alert( s[0] ); // Hello: - alert( s[1] ); // and - alert( s[2] ); // ! - - alert( v1 ); // Ilya - alert( v2 ); // Julia - - alert( s.raw[0] ); // Hello:\n - - return v1 + ' ♥ ' + v2; -} - -let mom = "Julia"; -let dad = "Ilya"; - -// s[0] | v1 | s[1] | v2 | s[2] -let str = love`Hello:\n ${mom} and ${dad}!`; - -alert(str); // 'Julia ♥ Ilya' -``` - -The string inside love`string` is split into pieces by embeds. The result is passed to `love`: - -- The first parameter `s` stores the pieces, here `s = ["Hello:\n ", " and ", "!"]`. -- The special proeprty `s.raw` contains unparsed values, the special characters are not processes. -- Then follow the values of embeds: `v1 = mom`, `v2 = data`. - -Templating functions allow to - - - - -- The first parameter `strings` is a - -In the example above, `love` is the name for the function. It is called with an array - - diff --git a/archive/commend.md b/archive/commend.md deleted file mode 100644 index acc2c27e..00000000 --- a/archive/commend.md +++ /dev/null @@ -1,22 +0,0 @@ -### Don't hesitate to comment - -Please, don't hesitate to comment. - -Comments increase the overall code footprint, but that's not a problem at all, because there are many tools which minify the code before publishing to production server. They remove comments, so they do not appear in the working scripts. - -The code clarity is what we should hunt for. And comments can really help to make it easier to understand. - -There are various types of comments, answering different questions: - -- What the code does? -- Why the code is written like that? -- Which counter-intuitive or implicit connections it has with other parts of the program? - -Further in the tutorial we'll make more notes about how to write the code better, easier to read and maintain. We'll also talk more about comments. - -```smart header="The good code is inherently readable and self-commenting" -Please note that the first type of comments ("what the code does") should be used to describe a "high-level" action, like the overall architecture, a function or a chunk of code. It's purpose is to give an overview, so a reader doesn't need to delve into the code and figure out. - -Novice programmers sometimes tend to elaborate too much. Please don't. The good code is inherently readable. No need to describe what few lines do. Unless it's something hard to grasp, and *then* it's worth to consider rewriting the code at the first place rather than commenting it. -``` - diff --git a/archive/descriptors.md b/archive/descriptors.md deleted file mode 100644 index 14f11009..00000000 --- a/archive/descriptors.md +++ /dev/null @@ -1,37 +0,0 @@ - - -## Property descriptors - -An object property is actually a more complex and tunable thing than just a "key-value" mapping. - -There are two kinds of properties. - -The first is *data properties*. - -They assiciate a key with the attributes: - -- **`value`** -- the value of the property. -- **`writable`** -- if `true`, can be changed, otherwise it's read-only. -- **`enumerable`** -- if `true`, then listed in loops, otherwise not listed. -- **`configurable`** -- if `true`, the property can be deleted and these attributes can be modified, otherwise not. - -All properties that we've seen yet were data properties. - -By default when a property is created, all attributes are `true`. - -We can get the the information about an existing property using [Object.getOwnPropertyDescriptor](mdn:js/Object/getOwnPropertyDescriptor): - - -```js run -let user = { - name: "John" -}; - -let descriptor = Object.getOwnPropertyDescriptor(user, 'name'); - -alert( descriptor.value ); // John -alert( descriptor.writable ); // true -alert( descriptor.enumerable ); // true -alert( descriptor.configurable ); // true -``` - diff --git a/archive/nfe.md b/archive/nfe.md deleted file mode 100644 index 7f7e2044..00000000 --- a/archive/nfe.md +++ /dev/null @@ -1,140 +0,0 @@ - -## Named Function Expression - -Named Function Expression or, shortly, NFE, is a term a Function Expression that has a name. - -For instance, let's take an ordinary Function Expression: - -```js -let sayHi = function(who) { - alert(`Hello, ${who}`); -}; -``` - -...And add a name to it: - -```js -let sayHi = function *!*func*/!*(who) { - alert(`Hello, ${who}`); -}; -``` - -What's the role of that additional `"func"` name? - -First let's note, that we're still having a Function Expression. Adding the name `"func"` after `function` did not make it a Function Declaration, because it is still created as a part of an assignment expression. - -Adding such a name also did not break anything. - -The function is still available as `sayHi()`: - -```js -//+ run -let sayHi = function *!*func*/!*(who) { - alert(`Hello, ${who}`); -}; - -sayHi("John"); // Hello, John -``` - -There are two special things about the name `func`: -
      -
    1. It allows to reference the function from inside itself.
    2. -
    3. It is not visible outside of the function.
    4. -
    - -For instance, the function `sayHi` below re-calls itself with `"Guest"` if no `who` is provided: - -```js -//+ run -let sayHi = function *!*func*/!*(who) { - if (who) { - alert(`Hello, ${who}`); - } else { -*!* - func("Guest"); // use func to re-call itself -*/!* - } -}; - -sayHi(); // Hello, Guest - -// But this won't work: -func(); // Error, func is not defined (not visible outside of the function) -``` - -Later we'll see more cases when a function wants to re-call itself with modified parameters. - -So, why won't we use `sayHi` for the nested call? - -Actually, in most cases we can: - -```js -let sayHi = function(who) { - if (who) { - alert(`Hello, ${who}`); - } else { -*!* - sayHi("Guest"); -*/!* - } -}; -``` - -The problem with the latter code is that the value of `sayHi` may change. The function may go to another variable: - -```js -//+ run -let sayHi = function *!*func*/!*(who) { - if (who) { - alert(`Hello, ${who}`); - } else { -*!* - func("Guest"); // (*) -*/!* - } -}; - -let welcome = sayHi; -sayHi = null; - -welcome(); // Hello, Guest (still works under different name) -``` - -Using `func` in the line `(*)` *guarantees* that this exactly function will be called. Using `sayHi` there - - -...But the name `func` is not visible outside of the function: - -```js -//+ run -let sayHi = function *!*func*/!*(who) { - // ... -}; - -*!* -func(); // Error: func is not defined -*/!* -``` - -Named Function Expressions are used in rare cases when: -
      -
    • The function needs to reference itself from inside. For instance, call itself with another arguments.
    • -
    • The function travels between variables.
    • -
    - -The code below demonstrates both conditions: - -```js -//+ run -let sayHi = function *!*func*/!*(name) { - if (name) { - alert(`Hello, ${name}!`) - } else { - func("Guest"); - } -}; - -welcome(); // Works -``` - - diff --git a/archive/promise/async-then.js b/archive/promise/async-then.js deleted file mode 100644 index 87150473..00000000 --- a/archive/promise/async-then.js +++ /dev/null @@ -1,60 +0,0 @@ - -````smart header="Handlers are always asynchronous, like `setTimeout(...,0)`" -Handlers assigned by `.then/catch` are always asynchronous. But if the promise is settled they run as soon as possible, similar to `setTimeout(...,0)`. - -Here's the example to demonstrate that: - -```js run -// the promise is immediately resolved with "done!" -let promise = new Promise(resolve => resolve("done!")); - -// alert runs asynchronously, like if it were wrapped in setTimeout(..., 0); -promise.then(alert); // (2) - -alert('code end'); // (1) -``` - -We'll first see "code end" `(1)`, and then "done!" `(2)`. - -Like if we had this instead of `(2)`: -```js -promise.then(result => setTimeout(() => alert(result), 0)); -``` - -The inner mechanics is like this: -- Promise handlers form a queue. -- When the current code is complete, the queue shifts and the next handler is executed. -```` - -````smart header="Functions resolve/reject accept at most one argument" -Functions `resolve/reject` accept only one argument. - -We can call them without any arguments too, that's the same as passing `undefined`: - -```js run -let promise = new Promise(resolve => resolve()); - -promise.then(alert); // undefined -``` - -...But if we pass many arguments: `resolve(1, 2, 3)`, then all arguments after the first one are ignored. -The idea is that a promise may have only one result (or an error). Use objects and destructuring if you need to pass many values, like this: - -```js run -let promise = new Promise(function(resolve, reject) { - let name = "John"; - let age = 25; - - resolve({name, age}); // "pack" the values in an object -}); - -// destructuring -promise.then(function({name, age}) { - // here we have name and age variables as if the promise had two results - alert(`${name} ${age}`); // John 25 -}) -``` - -```` - - diff --git a/archive/promise/fetch.js b/archive/promise/fetch.js deleted file mode 100644 index b4719af8..00000000 --- a/archive/promise/fetch.js +++ /dev/null @@ -1,37 +0,0 @@ -## Example: fetch - - -## Example: fetch - -Promises are also returned by some built-in browser methods. - -For instance, [fetch](https://fetch.spec.whatwg.org/#fetch-method) allows to load arbitrary content over the network. We can use it to send information to the server and load data from it. - -The syntax is: - -```js -let promise = fetch(url[, options]); -``` - -Here: -- `url` is the URL to load, -- `options` are various request options. - -There are many options, full information about them is in the [spec](https://fetch.spec.whatwg.org/#requestinit), here we won't need them. - -The promise returned by `fetch` resolves with the `response` object when the server responds. - -The most important properties of `response` are: -- `status` -- HTTP-code: 200 for OK, 404 for "Page not found" etc. -- `headers` -- HTTP headers. -- - -The important thing - - -```js run -fetch('/article/promise-chaining/1.html?speed=1') - .then(console.log); -``` - - diff --git a/archive/promise/thenable.js b/archive/promise/thenable.js deleted file mode 100644 index b72c0871..00000000 --- a/archive/promise/thenable.js +++ /dev/null @@ -1,23 +0,0 @@ -function loadScript(src) { - return new Promise(function(resolve, reject) { - let script = document.createElement('script'); - script.src = src; - - script.onload = () => resolve(script); - script.onerror = () => reject(new Error("Script load error: " + src)); - - document.head.append(script); - }); -} -loadScript("/article/promise-chaining/one.js") - .then(script => { - return { - then(resolve, reject) { - setTimeout(() => resolve(script), 1000); - } - }; - }) - .then(function(script) { - alert(one); - }); - diff --git a/archive/promise/thenable.md b/archive/promise/thenable.md deleted file mode 100644 index 7f528f13..00000000 --- a/archive/promise/thenable.md +++ /dev/null @@ -1,25 +0,0 @@ -````smart header="Thenables" -To be precise, any object that has a method `.then` is treated as a promise here. So we can use custom "promise-compatible" objects in the chain. Such objects are called "thenable". - -Here's an example: - -```js run -class Thenable { - constructor(result, delay) { - this.result = result; - } - then(resolve, reject) { - setTimeout(() => resolve(this.result * 2), delay); - } -}; - -new Promise(resolve => resolve(1)) - .then(result => { - return new Thenable(result, 1000); - }) - .then(alert); // shows 2 after 1000ms -``` - -That allows to use custom implementations of promises from 3rd-party libraries along with native promises. -```` - diff --git a/archive/promise/thenable2.js b/archive/promise/thenable2.js deleted file mode 100644 index 3b72aaf3..00000000 --- a/archive/promise/thenable2.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -new Promise() - .then(result => { - return { - then(resolve, reject) { - setTimeout(() => resolve("two"), 1000); - } - }; - }) - .then(result => { - console.log("HERE", result); - return result; - }) - .then(console.log) - .catch(err => console.error("ERROR", err)); - -// https://tc39.github.io/ecma262/#sec-promise-resolve-functions - diff --git a/archive/promise/whereto.txt b/archive/promise/whereto.txt deleted file mode 100644 index 2100b9b3..00000000 --- a/archive/promise/whereto.txt +++ /dev/null @@ -1,58 +0,0 @@ - -## Extending promises, thenables - -Promises are very simple by design. One of the thing they miss is the ability to cancel the process. - -For instance, `loadScript(src)` in previous examples returns a promise that allows to track success/failure of the loading. But can we abort it? No. - -We can inherit from `Promise` to introduce such functionality, like this: - - -```js run -function loadScript(src) { - let script = document.createElement('script'); - alert(1); - script.src = src; - - let promise = new Promise(function(resolve, reject) { - script.onload = () => { alert('onload'); resolve(script); } -*!* - script.onerror = err => reject(new Error("Script load error: " + src)); // (*) -*/!* - }); - - alert(2); - - document.head.append(script); - alert(3); - promise.abort = () => { - script.src = 'javascript:"" - '; - }; - return promise; -} - -let promise = loadScript("/article/promise-chaining/one.js?speed=0"); -promise.then(alert); -promise.abort(); -alert(4); -``` - - - - - - - -## Inheriting from promise, thenables, promise api, async/await - --------- - - -An object that has a method called `.then` is called a "thenable". - -Instead of checking if something is `instanceof Promise`, we should usually check it for being thenable, and if it is, then treat it as a promise ("duck typing"). - -JavaScript specification also checks the value returned by a handler for being a thenable, not exactly a promise, when it decides whether to pass it along the chain or wait for the result. So in the examples above we could use custom thenables instead of `Promise` instances. - -For instance, native promises give no way to "abort" the execution. The `loadScript` above cannot "cancel" script loading, just because there's no `.abort` method on promises, we can only listen for the state change using `.then/catch`. diff --git a/archive/proto/user.js b/archive/proto/user.js deleted file mode 100644 index e79d0b42..00000000 --- a/archive/proto/user.js +++ /dev/null @@ -1,16 +0,0 @@ -```js run -function User(name, birthday) { - let age = calcAge(); - - function calcAge() { - new Date().getFullYear() - birthday.getFullYear(); - } - - this.sayHi = function() { - alert(name + ', age:' + age); - }; -} - -let user = new User("John", new Date(2000,0,1)); -user.sayHi(); // John -``` diff --git a/archive/proto/wrong/javascript-prototype-confusion-and.html b/archive/proto/wrong/javascript-prototype-confusion-and.html deleted file mode 100644 index abc8f71a..00000000 --- a/archive/proto/wrong/javascript-prototype-confusion-and.html +++ /dev/null @@ -1,1353 +0,0 @@ - - - - - - - - - - - - - - - - - - - -Nowhere Near Ithaca: Javascript "Prototype" Confusion, and the Dubiously Useful "instanceof" - - - - - - - - -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    - -
    - - -
    - -
    -
    - -

    -Javascript "Prototype" Confusion, and the Dubiously Useful "instanceof" -

    -
    -
    -
    -
    - - - - - - - - - -
    - - - -

    Recently, I became aware that I was more confused than I realized regarding javascript's use of the word "prototype", as the word is used in two different ways. -

    -

    This draft note is the result of pondering on this a bit more. This pondering also resulted in some clarification (for me) of how the instanceof operator seems to work, and how its utility is doubtful. -

    - - - - - - -
    -Every object has a prototype, accessed via its "__proto__" property -
    - -

    Javascript objects are just bags of named things: properties. Properties can be other objects, functions (which are also objects), or primitives like numbers and strings.

    - -

    Every javascript object has a prototype, which can be accessed directly in most modern browsers via the named property __proto__.

    - -

    -When a property named foo is requested from an object obj via obj.foo, first the set of properties for object itself is searched for the property. If it is not found, then obj.__proto__ is searched for a property named foo. If not found there, then it searches obj.__proto__.__proto__, continuing up the "prototype chain" until it either finds the property or obj.__proto__.__proto__....__proto__ is null, and undefined is returned. -Note that the javascript engine is supposed to prevent cyclic loops in the prototype chain. -

    - - -

    Again: the name of the property for the prototype of an object is not "prototype": its name is "__proto__".

    - -

    That is one part of the potential confusion.

    - - - -
    -Every javascript function f has a property named "prototype" - which is not its prototype -
    - - -

    This is another part of the potential confusion.

    - -

    -f.prototypeis not the function's - prototype. -

    - -

    -As for any object, f.__proto__ is the function's prototype. -

    - -
    -What is the purpose of f.prototype? -
    - -

    Any function f can be used to generate new objects via newObject = new f(args). -When used this way, f is sometimes called the "constructor" for newObject. - -

    - -

    When an object is created from a function f via newObject = new f(args), the new object's prototype __proto__ -property is set to the property named "prototype" of f: -newObject.__proto__ = f.prototype .

    - -

    That is what f.prototype is used for.

    - -

    Note that there are other ways to create an object with a specified prototype, and in fact these other methods are recommended by some folks, avoiding the "new" keyword altogether.

    - -
    -Aside: The "constructor" Property -
    - -

    While every function can be used as a constructor, there is also a property named "constructor" for some objects.

    - -

    -In particular, for any function f, f.prototype.constructor = f. -

    - -

    Since objects created from f via new f(args) have their "__proto__" property initialized to f.prototype, this means that for any object newObject created via newObject = new f(args) for some function f, newObject.constructor will refer to the function used to create the object. Initially, at least, as you can change the constructor later. -

    - -

    Other than a record of the object's ancestry that might be useful in a handful of cases (that I've never encountered), I don't know how the knowledge of the constructor would be generally useful.

    - - -
    - What this has to do with how javascript's instanceof works -
    - -

    Javascript has an instanceof operator that returns true or false, and can be called like so: -

    obj instanceof f
    -
    -

    You can only use a function on the right side: instanceof will throw an error if f is not a function.

    - -

    The Mozilla Developer network summarizes this operator quite succinctly (I have used "function" instead of "constructor", since every function can be a constructor): - -

    -The instanceof operator tests whether an object has in its prototype chain the prototype property of a given function. -
    - -

    - - - - - - - - -

    This is illustrated in the figure below.

    - - - - - -
    - -
    -(obj instanceof f -) is true -if f.prototype is equal to -
    -any __proto__ in -the prototype chain of obj -
    - -
    Do People Use instanceof?
    - -

    Answer: I think few do.

    - - - -

    When queried on twitter, both Eric Elliot and Kyle Simpson (two javascript folks I think a lot of) tweeted back that they never did. When I asked on hacker news, one commenter said it was a code smell, while another said it was useful when checking if an object is an array (it should be noted that jquery checks the result of a toString call to determine if something is an array).

    - -

    There are also problems with trying to use instanceof across iframes.

    - -

    @kangax discourages its use (2009). He also recommends the same method jquery uses to check if something is an array, btw.

    - -

    Crockford has remarked (in 2003) about the useless instanceof operator (link via kangax's article).

    - -

    So, I don't foresee using it much myself, but it is personally satisfying to come to a better understanding of it and the surrounding javascript constructs.

    - - - - - - -
    -And be Warned... -
    - - -

    Compared to "standard" OOP that can result in rigid, iron-like structures that complicate change and reuse, javascript with its prototype-based reuse pattern is as firm as a jello: you can change things bit more willy-nilly, if you so desire.

    - -

    In particular, you can muck with the prototype and constructor properties after-the-fact, and this would likely invalidate the notes above in whatever curious ways you (or the code you are using) has mucked with things.

    - - - -
    -
    -
    - -
    - -
    -
    - -
    - -
    -
    - -Newer Post - - -Older Post - -Home -
    -
    -
    - -
    - -
    -

    Popular Posts

    - -
    -
    -
    -
    -
    - -
    -
    -
    -
    - -
    -
    -
    -
    - -
    - -
    -
    -
    -
    -
    -
    -
    -
    - -
    - -
    -
    -
    -
    -
    -
    -
    -
    - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/archive/recursion.md b/archive/recursion.md deleted file mode 100644 index 4b142bd4..00000000 --- a/archive/recursion.md +++ /dev/null @@ -1,283 +0,0 @@ -# Recursion, stack - -It's ok for a function to rely on other functions for sub-tasks. - -We've already been using it when `welcome()` relied on `alert()` call to show the message. - -In particular, a function can make a sub-call *itself*. That's called *a recursion*. - -We'll fiddle around that advanced case to better learn how functions work. - -[smart header="A topic you already know?"] -Recursion is a general programming term. If you are already familiar with it, then you may list the page to the next chapter. Please read on if you are new to functions or just prefer not to skip parts. -[/smart] - -## Divide and conquer - -Divide and conquer (or "divide and rule") is an ancient strategy attributed to Philip II of Macedon and mentioned by the Roman emperor Julius Caesar, the French emperor Napolen and many other leaders. - -They used it to rule, but the similar thing is often done in programming. If we have a complex task, that we're not sure how to solve as a whole, then maybe we can split it and try to solve the smaller parts. - -And if smaller parts are still too big, then let's cut them and try to solve even smaller parts. - -Repeat the cutting until the parts are so small that it's obvious how to deal with them. - -Sounds good? Now let's explore a case of this approach. - -## Eating an elephant - -Let's say we have a task "to eat an elephant". But how? - -The well-known humorous solution is: "piece by piece". We cut a piece, eat it and repeat the process. Sooner or later, the elephant is eaten. - -The algorithm can be reflected in the code: - -``` -function eat(elephant) { - cut a piece from the elephant - eat it - if (something left) { -*!* - eat(what's left of the elephant) // (*) -*/!* - } -} -``` - -The recursion occurs at line `(*)`: function `eat` after making things simpler passes the remaining data again to itself. - -Of course that's only one variant. For example, we could cut the elephant in 2 halves, then cut the halves in half again etc, until the parts are small enough to eat. Then put them into plates and pass to the guests. - -The core idea is the same: splitting the problem into multiple subproblems and doing the same with them if they're still big. - -## A power of a number - - - -## Степень pow(x, n) через рекурсию - -В качестве первого примера использования рекурсивных вызовов -- рассмотрим задачу возведения числа `x` в натуральную степень `n`. - -Её можно представить как совокупность более простого действия и более простой задачи того же типа вот так: - -```js -pow(x, n) = x * pow(x, n - 1) -``` - -То есть, xn = x * xn-1. - -Например, вычислим `pow(2, 4)`, последовательно переходя к более простой задаче: - -
      -
    1. `pow(2, 4) = 2 * pow(2, 3)`
    2. -
    3. `pow(2, 3) = 2 * pow(2, 2)`
    4. -
    5. `pow(2, 2) = 2 * pow(2, 1)`
    6. -
    7. `pow(2, 1) = 2`
    8. -
    - -На шаге 1 нам нужно вычислить `pow(2,3)`, поэтому мы делаем шаг 2, дальше нам нужно `pow(2,2)`, мы делаем шаг 3, затем шаг 4, и на нём уже можно остановиться, ведь очевидно, что результат возведения числа в степень 1 -- равен самому числу. - -Далее, имея результат на шаге 4, он подставляется обратно в шаг 3, затем имеем `pow(2,2)` -- подставляем в шаг 2 и на шаге 1 уже получаем результат. - -Этот алгоритм на JavaScript: - -```js -//+ run -function pow(x, n) { - if (n != 1) { // пока n != 1, сводить вычисление pow(x,n) к pow(x,n-1) - return x * pow(x, n - 1); - } else { - return x; - } -} - -alert( pow(2, 3) ); // 8 -``` - -Говорят, что "функция `pow` *рекурсивно вызывает сама себя*" до `n == 1`. - -Значение, на котором рекурсия заканчивается называют *базисом рекурсии*. В примере выше базисом является `1`. - -Общее количество вложенных вызовов называют *глубиной рекурсии*. В случае со степенью, всего будет `n` вызовов. - -Максимальная глубина рекурсии в браузерах ограничена, точно можно рассчитывать на `10000` вложенных вызовов, но некоторые интерпретаторы допускают и больше. - -Итак, рекурсию используют, когда вычисление функции можно свести к её более простому вызову, а его -- ещё к более простому, и так далее, пока значение не станет очевидно. - -## Контекст выполнения, стек - -Теперь мы посмотрим, как работают рекурсивные вызовы. Для этого мы рассмотрим, как вообще работают функции, что происходит при вызове. - -**У каждого вызова функции есть свой "контекст выполнения" (execution context).** - -Контекст выполнения -- это служебная информация, которая соответствует текущему запуску функции. Она включает в себя локальные переменные функции и конкретное место в коде, на котором находится интерпретатор. - -Например, для вызова `pow(2, 3)` из примера выше будет создан контекст выполнения, который будет хранить переменные `x = 2, n = 3`. Мы схематично обозначим его так: - -
      -
    • Контекст: { x: 2, n: 3, строка 1 }
    • -
    - -Далее функция `pow` начинает выполняться. Вычисляется выражение `n != 1` -- оно равно `true`, ведь в текущем контексте `n=3`. Поэтому задействуется первая ветвь `if` : - -```js -function pow(x, n) { - if (n != 1) { // пока n != 1 сводить вычисление pow(x,n) к pow(x,n-1) -*!* - return x * pow(x, n - 1); -*/!* - } else { - return x; - } -} -``` - -Чтобы вычислить выражение `x * pow(x, n-1)`, требуется произвести запуск `pow` с новыми аргументами. - -**При любом вложенном вызове JavaScript запоминает текущий контекст выполнения в специальной внутренней структуре данных -- "стеке контекстов".** - -Затем интерпретатор приступает к выполнению вложенного вызова. - -В данном случае вызывается та же `pow`, однако это абсолютно неважно. Для любых функций процесс одинаков. - -Для нового вызова создаётся свой контекст выполнения, и управление переходит в него, а когда он завершён -- старый контекст достаётся из стека и выполнение внешней функции возобновляется. - -Разберём происходящее с контекстами более подробно, начиная с вызова `(*)`: - -```js -//+ run -function pow(x, n) { - if (n != 1) { // пока n!=1 сводить вычисление pow(..n) к pow(..n-1) - return x * pow(x, n - 1); - } else { - return x; - } -} - -*!* -alert( pow(2, 3) ); // (*) -*/!* -``` - -
    -
    `pow(2, 3)`
    -
    Запускается функция `pow`, с аргументами `x=2`, `n=3`. Эти переменные хранятся в контексте выполнения, схематично изображённом ниже: - -
      -
    • Контекст: { x: 2, n: 3, строка 1 }
    • -
    -Выполнение в этом контексте продолжается, пока не встретит вложенный вызов в строке 3. -
    -
    `pow(2, 2)`
    -
    В строке `3` происходит вложенный вызов `pow` с аргументами `x=2`, `n=2`. Текущий контекст сохраняется в стеке, а для вложеннного вызова создаётся новый контекст (выделен жирным ниже): - -
      -
    • Контекст: { x: 2, n: 3, строка 3 }
    • -
    • Контекст: { x: 2, n: 2, строка 1 }
    • -
    -Обратим внимание, что контекст включает в себя не только переменные, но и место в коде, так что когда вложенный вызов завершится -- можно будет легко вернуться назад. - -Слово "строка" здесь условно, на самом деле, конечно, запомнено более точное место в цепочке команд. -
    -
    `pow(2, 1)`
    -
    Опять вложенный вызов в строке `3`, на этот раз -- с аргументами `x=2`, `n=1`. Создаётся новый текущий контекст, предыдущий добавляется в стек: -
      -
    • Контекст: { x: 2, n: 3, строка 3 }
    • -
    • Контекст: { x: 2, n: 2, строка 3 }
    • -
    • Контекст: { x: 2, n: 1, строка 1 }
    • -
    -На текущий момент в стеке уже два старых контекста. -
    -
    Выход из `pow(2, 1)`.
    -
    При выполнении `pow(2, 1)`, в отличие от предыдущих запусков, выражение `n != 1` будет равно `false`, поэтому сработает вторая ветка `if..else`: - -```js -function pow(x, n) { - if (n != 1) { - return x * pow(x, n - 1); - } else { -*!* - return x; // первая степень числа равна самому числу -*/!* - } -} -``` - -Здесь вложенных вызовов нет, так что функция заканчивает свою работу, возвращая `2`. Текущий контекст больше не нужен и удаляется из памяти, из стека восстанавливается предыдущий: - -
      -
    • Контекст: { x: 2, n: 3, строка 3 }
    • -
    • Контекст: { x: 2, n: 2, строка 3 }
    • -
    -Возобновляется обработка внешнего вызова `pow(2, 2)`. -
    -
    Выход из `pow(2, 2)`.
    -
    ...И теперь уже `pow(2, 2)` может закончить свою работу, вернув `4`. Восстанавливается контекст предыдущего вызова: -
      -
    • Контекст: { x: 2, n: 3, строка 3 }
    • -
    -Возобновляется обработка внешнего вызова `pow(2, 3)`. -
    -
    Выход из `pow(2, 3)`.
    -
    Самый внешний вызов заканчивает свою работу, его результат: `pow(2, 3) = 8`.
    -
    - -Глубина рекурсии в данном случае составила: **3**. - -Как видно из иллюстраций выше, глубина рекурсии равна максимальному числу контекстов, одновременно хранимых в стеке. - -Обратим внимание на требования к памяти. Рекурсия приводит к хранению всех данных для неоконченных внешних вызовов в стеке, в данном случае это приводит к тому, что возведение в степень `n` хранит в памяти `n` различных контекстов. - -Реализация возведения в степень через цикл гораздо более экономна: - -```js -function pow(x, n) { - let result = x; - for let i = 1; i < n; i++) { - result *= x; - } - return result; -} -``` - -У такой функции `pow` будет один контекст, в котором будут последовательно меняться значения `i` и `result`. - -**Любая рекурсия может быть переделана в цикл. Как правило, вариант с циклом будет эффективнее.** - -Но переделка рекурсии в цикл может быть нетривиальной, особенно когда в функции, в зависимости от условий, используются различные рекурсивные подвызовы, когда ветвление более сложное. - -## Итого - -Рекурсия -- это когда функция вызывает сама себя, как правило, с другими аргументами. - -Существуют много областей применения рекурсивных вызовов. Здесь мы посмотрели на один из них -- решение задачи путём сведения её к более простой (с меньшими аргументами), но также рекурсия используется для работы с "естественно рекурсивными" структурами данных, такими как HTML-документы, для "глубокого" копирования сложных объектов. - -Есть и другие применения, с которыми мы встретимся по мере изучения JavaScript. - -Здесь мы постарались рассмотреть происходящее достаточно подробно, однако, если пожелаете, допустимо временно забежать вперёд и открыть главу [](/debugging-chrome), с тем чтобы при помощи отладчика построчно пробежаться по коду и посмотреть стек на каждом шаге. Отладчик даёт к нему доступ. - - - -[head] - -[/head] - diff --git a/archive/timing-decorator.md b/archive/timing-decorator.md deleted file mode 100644 index b412f5c4..00000000 --- a/archive/timing-decorator.md +++ /dev/null @@ -1,105 +0,0 @@ - - -## Instrumentation: timing decorator - -Let's say we have a function and want to measure time it takes to run. - -Of course, we could modify it. Add something like `timerStart()` to the start and `timerEnd()` to all exit points. Then later we may want to log which arguments it receives and results. That requires additional code as well. - -That is called [instrumentation](https://en.wikipedia.org/wiki/Instrumentation) of the code -- adding stuff to measure times, log what's happening and do other watching/measuring without interfering with the main functionality. - -Putting instrumentation inside the function manually is not pretty at all. It takes space, shadows the core functionality and makes it harder to debug. - -There are tools that analyze javascript code and add instrumentation calls to it automatically. But here we'll take a "median" approach. We will "wrap" instrumentation over function without touching its code. - -What we going to do is a special function `timingDecorator(func)`, that takes a function `func` and returns a "wrapper" around it, that transfers all calls to `func` and measures time they take. - -For simplicity let's assume that `func` has only one argument. - -The code with `timingDecorator` and example function: - - - - -```js run -function fibo(n) { // a function to measure, here we count fibonacci number - return (n > 2) ? fibo(n - 1) + fibo(n - 2) : 1; -} - -let timers = {}; // timers to store data - -function timingDecorator(func) { - return function(x) { - let start = performance.now(); - - let result = func(x); - - let time = performance.now() - start; - - if (!timers[func.name]) timers[func.name] = 0; - timers[func.name] += time; - - return result; - }; -} - -// decorate it -fibo = timingDecorator(fibo); - -// run -alert( fibo(10) ); // 55 -alert( fibo(20) ); // 6765 -alert( fibo(30) ); // 832040 - -alert( `Total time: ${timers.fibo.toFixed(3)}ms` ); // total count of fibo calls -``` - -При помощи декоратора `timingDecorator` мы сможем взять произвольную функцию и одним движением руки прикрутить к ней измеритель времени. - -Его реализация: - -```js run -let timers = {}; - -// прибавит время выполнения f к таймеру timers[timer] -function timingDecorator(f, timer) { - return function() { - let start = performance.now(); - - let result = f.apply(this, arguments); // (*) - - if (!timers[timer]) timers[timer] = 0; - timers[timer] += performance.now() - start; - - return result; - } -} - -// функция может быть произвольной, например такой: -let fibonacci = function f(n) { - return (n > 2) ? f(n - 1) + f(n - 2) : 1; -} - -*!* -// использование: завернём fibonacci в декоратор -fibonacci = timingDecorator(fibonacci, "fibo"); -*/!* - -// неоднократные вызовы... -alert( fibonacci(10) ); // 55 -alert( fibonacci(20) ); // 6765 -// ... - -*!* -// в любой момент можно получить общее количество времени на вызовы -alert( timers.fibo + 'мс' ); -*/!* -``` - -Обратим внимание на строку `(*)` внутри декоратора, которая и осуществляет передачу вызова: - -```js -let result = f.apply(this, arguments); // (*) -``` - -Этот приём называется "форвардинг вызова" (от англ. forwarding): текущий контекст и аргументы через `apply` передаются в функцию `f`, так что изнутри `f` всё выглядит так, как была вызвана она напрямую, а не декоратор.