course js day 4

30
JavaScript Georgy Grigoryev, Auriga, Inc.

Transcript of course js day 4

Page 1: course js day 4

JavaScript

Georgy Grigoryev, Auriga, Inc.

Page 2: course js day 4

2

1 вебинар

История js

Стандарт ECMAScript

IDE и редакторы

Запуск и отладка скриптов

Типы и операторы

Page 3: course js day 4

3

2 вебинар

Массивы

Основные конструкции языка, и их применение

Объекты и JSON

Регулярные выражения

Контекст, this, bind, call, apply

ООП, прототипы, ООП в ECMAScript 6

Page 4: course js day 4

4

3 вебинар

JavaScript и HTML

Работа с DOM

События, таймеры и AJAX

Page 5: course js day 4

5

4 вебинар

jQuery

AngularJS

Knockout, Ember, Backbone

CoffeeScript

Node.js

Page 6: course js day 4

6

jQuery.ajax

$.ajax.html<html><head>

<title>jQuery AJAX</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script><script>

function load_data() {$.ajax({

url: "data.html"}).done(

function (data) {document.getElementById("target").innerHTML = data

}).fail(

function () {alert("error when call server")

});}

</script></head><body>

<button type="button" onclick="load_data()">Load</button><p id="target"></p>

</body></html>

Page 7: course js day 4

7

jQuery

jQuery – самый популярный, свободно распространяемый, js

фреймворк

jQuery.UI – библиотека ui элементов основанная на jQuery

jQuery – имеет большую экосистему, создано огромное

количество плагинов

jQuery – имеет относительно большой вес (~ 100 КБ)

jQuery – кроссбраузерна (версия 1.хх поддерживает IE6!)

Page 8: course js day 4

8

jQuery

<html><head>

<title>jQuery</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

</head><body>

<script type="text/javascript">console.log($);console.log($(document));

</script></body></html>

$.html

Page 9: course js day 4

9

jQuery selectors

<html><head>

<title>jQuery selectors</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script><script type="text/javascript">

$(document).ready(function () {console.log($("span"));console.log($(".main_p"));

})</script>

</head><body>

<div><p class="main_p">

<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sit amet feugiat ipsum.</span><br /><span>Phasellus quis magna nulla. Ut non ornare metus, sit amet posuere dui.</span><br /><span>Quisque placerat libero lacus, sit amet cursus mauris scelerisque vel.</span><br /><span>Nunc ipsum justo, tempor sed felis in, porta elementum erat. Ut scelerisque iaculis sapien.</span><br /><span>Integer a elit ultrices nisi gravida faucibus vitae non lacus.</span><br /><span>Vestibulum convallis sagittis imperdiet. Donec lacinia sollicitudin tincidunt. Morbi vel viverra arcu, in convallis est.</span>

</p></div>

</body></html>

jquery selectors.html

Page 10: course js day 4

10

Onload vs $(document).ready

onload vs $(document).ready.html<html><head>

<title>load event</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script><script type="text/javascript">

var counter = 1;log_msg('head loaded')function log_msg(message) {

console.log(message + ", counter = " + counter);var arr_p = [];for (var i = 0; i < document.getElementsByTagName('p').length; i++) {

arr_p.push(document.getElementsByTagName('p')[i]);}console.log(arr_p);counter++;

}window.onload = log_msg.bind(null, 'window loaded');$(document).ready(function () { log_msg("jQuery document ready") });

</script></head><body onload="log_msg('body loaded');">

<p>Paragraph 1</p><img src="http://localhost:1515/get_image.ashx" /><script type="text/javascript">log_msg("inline call");</script><p>Paragraph 2</p>

</body></html>

Page 11: course js day 4

11

Simple progress bar

jquery simple progress bar.html<html><head>

<title>load event</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script><script type="text/javascript" src="progress_bar.js"></script>

</head><body onload="log_msg('body loaded');">

<p>Paragraph 1</p><img src="http://localhost:1515/get_image.ashx" style="height:200" /><script type="text/javascript">log_msg("inline call");</script><p>Paragraph 2</p>

</body></html>

var counter = 1;log_msg('head loaded')function log_msg(message) {

console.log(message + ": counter = " + counter);var arr_p = [];for (var i = 0; i < document.getElementsByTagName('p').length; i++) {

arr_p.push(document.getElementsByTagName('p')[i]);}console.log(arr_p);counter++;

}var window_loaded = false;window.onload = function () {

log_msg('window loaded');window_loaded = true;$("#div_bar").remove();

}$(document).ready(function () {

log_msg("jQuery document ready");if (!window_loaded) {

var div_bar = $('<div id="div_bar" style="position:fixed; top:0; left:0; background-color:rgba(0,0,0,0.6) "/>').css("height", window.innerHeight).css("width",window.innerWidth);

div_bar.append($('<div style="position:fixed;top:40%;left:48%;color:#fff"/>').text("loading..."));

$("body").append(div_bar);}

});

progress_bar.js

Page 12: course js day 4

12

jquery each

jquery each.html<html><head>

<title>jQuery array iterator</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script><script type="text/javascript">

$(document).ready(function () {$.each($("span"), function (i, val) {

console.log(i);console.log(val);

});})

</script></head><body>

<div><p class="main_p">

<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sit amet feugiat ipsum.</span><br /><span>Phasellus quis magna nulla. Ut non ornare metus, sit amet posuere dui.</span><br /><span>Quisque placerat libero lacus, sit amet cursus mauris scelerisque vel.</span><br /><span>Nunc ipsum justo, tempor sed felis in, porta elementum erat. Ut scelerisque iaculis sapien.</span><br /><span>Integer a elit ultrices nisi gravida faucibus vitae non lacus.</span><br /><span>Vestibulum convallis sagittis imperdiet. Donec lacinia sollicitudin tincidunt. Morbi vel viverra arcu, in convallis est.</span>

</p></div>

</body></html>

Page 13: course js day 4

13

jQuery.ajax

$.ajax.html<html><head>

<title>jQuery AJAX</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script><script>

function load_data() {$.ajax({

url: "http://localhost:1515/get_json.ashx"}).done(

function (data) {$(data).each(function (i, lang) {

var option = $("<option />").val(lang.Name).text(lang.Name);$("#langs").append(option);

});}

).fail(function () {

alert("error when call server");});

}</script>

</head><body>

<button type="button" onclick="load_data()">Load</button><select id="langs"></select>

</body></html>

Page 14: course js day 4

14

$.getJSON

<html><head>

<title>jQuery AJAX</title><script src="http://code.jquery.com/jquery-2.1.1.min.js"></script><script>

function load_data() {$.getJSON("http://localhost:1515/get_json.ashx").done(

function (data) {$(data).each(function (i, lang) {

var option = $("<option />").val(lang.Name).text(lang.Name);$("#langs").append(option);

});}

).fail(function () {

alert("error when call server");});

}</script>

</head><body>

<button type="button" onclick="load_data()">Load</button><select id="langs"></select>

</body></html>

$.getJSON.html

Page 15: course js day 4

15

getJSON, post

$.ajax({dataType: "json",url: url,data: data,success: success

});

$.getJSON()

$.ajax({type: "POST",url: url,data: data,success: success,dataType: dataType

});

$.post()

Page 16: course js day 4

16

jQuery.UI

Из коробки поддерживает большое количество UI эффектов

Состоит из js скрипта и css файла темы

Темы оформления активно разрабатываются сообществом

Несколько стандартных виджетов

Сборку jquery.ui можно кастомизировать

Page 17: course js day 4

17

jQuery.UI draggable

<html lang="en"><head>

<meta charset="utf-8"><title>jQuery UI Draggable - Default functionality</title><script src="https://code.jquery.com/jquery-1.10.2.js"></script><script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script><link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/ui-lightness/jquery-ui.css"><style>

#draggable {width: 150px;height: 150px;padding: 0.5em;

}</style><script>

$(function () {$("#draggable").draggable();

});</script>

</head><body>

<div id="draggable" class="ui-widget-content"><p>Drag me around</p>

</div></body></html>

Source: http://jqueryui.com/draggable/

Page 18: course js day 4

18

jQuery.datepicker

<html lang="en"><head>

<meta charset="utf-8"><title>jQuery UI Datepicker - Default functionality</title><script src="https://code.jquery.com/jquery-1.10.2.js"></script><script src="https://code.jquery.com/ui/1.11.1/jquery-ui.js"></script><link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/ui-

lightness/jquery-ui.css"><script>

$(function () {$("#datepicker").datepicker();

});</script>

</head><body>

<p>Date:<input type="text" id="datepicker">

</p>

</body></html>

$.datepicker.html

Page 19: course js day 4

19

jQuery pros

Очень функциональная библиотека

Низкий порог вхождения

Большое количество расширений и плагинов

Хорошая инфраструктура, легко использовать для

макетной разработки

Кроссбраузерна (IE6+ или IE9+)

Page 20: course js day 4

20

jQuery cons

Весит порядка 100КБ

Большая часть функционала легко реализуема

на js

Page 21: course js day 4

21

AngularJS

<html ng-app><head>

<title>AngularJS</title><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-

beta.17/angular.min.js"></script></head><body>

<div><label>Name:</label><input type="text" ng-model="yourName" placeholder="Enter a name here"><hr><h1>Hello {{yourName}}!</h1>

</div></body></html>

AngularJS.html

Page 22: course js day 4

22

AngularJS

Превращает HTML+JS+CSS в MVC приложение

Развивается Google и сообществом

Размер сжатого ~ 110 КБ

Многократно повышает отзывчивость сайта

Имеет некоторые встроенные эффекты

Page 23: course js day 4

23

<html ng-app><head>

<title>AngularJS</title><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script><script type="text/javascript">

function UserController($scope) {$scope.User = {

Name: "",WelcomeMessage: function () {

return "Hello " + $scope.User.Name + "!";}

};}

</script></head><body>

<div ng-app="" ng-controller="UserController"><label>Name:</label><input type="text" ng-model="User.Name" placeholder="Enter a name here"><hr><h1>{{User.WelcomeMessage()}}</h1>

</div>

</body></html>

AngularJS controllers

AngularJS controllers.html

Page 24: course js day 4

24

AngularJS

<html ng-app>

<input type="text" ng-model="yourName" placeholder="Enter a name here">

Специальные HTML директивы AngularJS

<h1>Hello {{yourName}}!</h1>Двойные фигурные скобки для работы с представлением

<div ng-app="" ng-controller="UserController">

function UserController($scope) {

Контроллеры объявляются через директивы

Page 25: course js day 4

25

AngularJS example

http://angular.github.io

Page 26: course js day 4

26

NodeJS

JavaScript Back-end

Использует Google V8

Кроссплатформенный

Имеет свой менеджер пакетов

https://github.com/joyent/node

Page 27: course js day 4

27

node-webkit

Состоит из Chromium+Node.js

Кроссплатформенный

https://github.com/rogerwang/node-webkit

Page 28: course js day 4

28

github Atom

https://atom.io/

Page 29: course js day 4

29

KnockoutJS

MVVM

Создан сотрудником Microsoft, лицензия MIT

Содержит UI элементы

Page 30: course js day 4

30

Contacts

Thank You and

We Look Forward to Working with You

Auriga, USA 92 Potter Rd, Ste 1Wilton, NH 03086, USAPhone: +1 (866) 645-1119Fax: +1 (603) [email protected] www.auriga.com

Auriga, Russia125 Varshavskoe Shosse, Unit 16A

Moscow, 117587Tel:+7 (495) 713-9900 Fax:+7 (495) 939-0300

[email protected] www.auriga.com