Front End Development: The Important Parts

82
FRONT END DEVELOPMENT by Sergey N. Bolshchikov The Important Parts

description

The important parts of the front end development sphere including CSS3, advanced JavaScript, libraries such as jQuery, RequireJS and Promises. And finally, chrome developer tools for successful debugging and editing.

Transcript of Front End Development: The Important Parts

Page 1: Front End Development: The Important Parts

FRONT END DEVELOPMENT

by Sergey N

. BolshchikovThe Important Parts

Page 2: Front End Development: The Important Parts

3 hours of wasting my time?

Page 3: Front End Development: The Important Parts

Let's find out

Page 4: Front End Development: The Important Parts

LET'S FIND OUT

1. Is it possible to do shadows with CSS?

Page 5: Front End Development: The Important Parts

LET'S FIND OUT

1. Is it possible to do shadows with CSS?

2. Who can write such function?

var result = addNumbers(2)(3);

Page 6: Front End Development: The Important Parts

LET'S FIND OUT

1. Is it possible to do shadows with CSS?

2. Who can write such function?

var result = addNumbers(2)(3);

3. Who can define "this"?

Page 7: Front End Development: The Important Parts

LET'S FIND OUT

1. Is it possible to do shadows with CSS?

2. Who can write such function?

var result = addNumbers(2)(3);

3. Who can define "this"?

4. How to call a function after completion of

two async functions together?

Page 8: Front End Development: The Important Parts

OUTLINEI. CSS

1. Basics2. CSS33. LESS

II. JavaScript1. Functions: objects2. Lexical scope: closures, module pattern3. Execution contexts and "this" value

III. Tools and Libraries1. RequireJS2. jQuery3. Promises4. Chrome Dev Tools

Page 9: Front End Development: The Important Parts

CSS

Page 10: Front End Development: The Important Parts

CSS :: SELECTORS

Selector Description Example

*

Matches any element.

E Matches any E element (i.e., an element of type E).

a

E F Matches any F element that is a descendant of an E element.

div a

E > F Matches any F element that is a child of an element E.

div > a

E:first-child Matches element E when E is the first child of its parent.

li:first-child

E:linkE:visited

Matches element E if E is the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited).

a:linka:visited

Page 11: Front End Development: The Important Parts

CSS :: SELECTORS (cont.)

Selector Description Example

E:activeE:hoverE:focus

Matches E during certain user actions.

a:activea:hovera:focus

E + F Matches any F element immediately preceded by a sibling element E.

div + div

E[foo] Matches any E element with the "foo" attribute set (whatever the value).

div[data-id]

E[foo="warning"] Matches any E element whose "foo" attribute value is exactly equal to "warning".

input[type=”text”]

DIV.warning Language specific. (In HTML, the same as DIV[class~="warning"].)

div.navigation

E#myid Matches any E element with ID equal to "myid".

div#main

Page 12: Front End Development: The Important Parts

CSS :: BOX MODEL

Page 13: Front End Development: The Important Parts

CSS :: MORE● display: [none, block, inline, table, inline-

block...],

● position: [absolute, fixed, relative],

● top: [number],

● left: [number],

● float: [left, right, none]

● font: size, weight, family

Page 14: Front End Development: The Important Parts

CSS :: CSS3

● border-radius

● box-shadow

● gradients

● multiple columns

● transformations

● animation

http://jsbin.com/udimij/1/edit

Page 15: Front End Development: The Important Parts

LESS

Page 16: Front End Development: The Important Parts

LESS :: WHY?

● CSS is too much writing

.nav {}

.nav ul {}

.nav ul li {}

● No validation

● Declarative

Page 17: Front End Development: The Important Parts

LESS :: WHAT?

LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.

Page 18: Front End Development: The Important Parts

LESS :: NESTING

.nav {ul {...li {...

}}

}

Page 19: Front End Development: The Important Parts

LESS :: VARIABLES

@color: #4D926F;

#header {color: @color;

}h2 { color: @color;}

#header { color: #4D926F;}h2 { color: #4D926F;}

Page 20: Front End Development: The Important Parts

LESS :: MIXINS.border-radius (@radius) { border-radius: @radius; -moz-border-radius: @radius; -webkit-border-radius: @radius;}

#header { .border-radius(4px);}

.button { .border-radius(6px);}

#header { border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px;}

.button { border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px;}

Page 21: Front End Development: The Important Parts

FUNCTIONSin

JAVASCRIPT

Page 22: Front End Development: The Important Parts

FUNCTION is an

OBJECT

Page 23: Front End Development: The Important Parts

FUNCTIONS :: OBJECTSfunction foo (x) { return x + 1;}

function bar (y) { return y * 2;}

var myFuncs = [foo, bar];myFuncs[0](2) // 3

Page 24: Front End Development: The Important Parts

FUNCTIONS :: OBJECTSvar callFirst = function (x) { return x + 1;}

var callSecond = function (f, x) { return f(f(x));}

var attempt = callSecond(callFirst, 2); // 4

Page 25: Front End Development: The Important Parts

FUNCTIONS :: OBJECTSvar makeFunc = function () { var addOne = function (x) { return x + 1; } return addOne;}

var f = makeFunc();f(3); // 4

Page 26: Front End Development: The Important Parts

LEXICALENVIRONMENT

Page 27: Front End Development: The Important Parts

FUNCTIONS :: LEXICAL ENV :: def

Definition:

A Lexical Environment is a specification type used to define the association of Identifiers to specific variables and functions based upon the lexical nesting structure of ECMAScript code.

Page 28: Front End Development: The Important Parts

FUNCTIONS :: LEXICAL ENV :: wtf

function () {...function () {

...return;

}

return ;}

Lexical Env Outers

Lexical Env Inner

Page 29: Front End Development: The Important Parts

FUNCTIONS :: LEXICAL ENV :: nestingfunction createIncreaser () { var accumulator = 0; var increaser = function () { return accumulator += 2; }; return increaser;}

var inc = createIncreaser();console.log(inc()); // 2console.log(inc()); // 4console.log(inc()); // 6

Page 30: Front End Development: The Important Parts

FUNCTIONS :: LEXICAL ENV :: closurefunction createIncreaser () { var accumulator = 0; var increaser = function () { return accumulator += 2; }; return increaser;}

var inc = createIncreaser();console.log(inc()); // 2console.log(inc()); // 4console.log(inc()); // 6

env

code block

Page 31: Front End Development: The Important Parts

FUNCTIONS :: LEXICAL ENV :: module pattern// not a constructorvar myModule = (function (projId) { var moduleName, projectorId; moduleName = 'toolbar'; projectorId = projId; return { init: function () { console.log(moduleName); }, tickUpdate: function () {} };})();

myModule.init() // "toolbar"myModule.moduleName // undefined

Page 32: Front End Development: The Important Parts

PROBLEM

<div> I am div 1</div>

<div> I am div 2</div>

<div> I am div 3</div>

Page 33: Front End Development: The Important Parts

PROBLEM

<div> I am div 1</div>

<div> I am div 2</div>

<div> I am div 3</div>

var i, divs, len; i = 0;divs=document.getElementsByTagName('div');len = divs.length;

for (i; i < len; i += 1) { divs[i].addEventListener('click', function () {

alert('I am div ' + i); }, false)}

http://jsbin.com/acoceb/1/edit

Page 34: Front End Development: The Important Parts

PROBLEM

environmentvar i

eventhandler 1

eventhandler 2

eventhandler 3

Page 35: Front End Development: The Important Parts

PROBLEM

<div> I am div 1</div>

<div> I am div 2</div>

<div> I am div 3</div>

var i, divs, len;

i = 0;divs = document.getElementsByTagName('div');len = divs.length;

for (i; i < len; i += 1) { (function (id) { divs[i].addEventListener('click',

function () { alert("I am div " + (id + 1)); }, false); })(i);}

http://jsbin.com/acoceb/5/edit

Page 36: Front End Development: The Important Parts

PROBLEM

environment

eventhandler 1

eventhandler 2

eventhandler 3

var i var i var i

Page 37: Front End Development: The Important Parts

EXECUTIONCONTEXT

Page 38: Front End Development: The Important Parts

FUNCTIONS :: EXECUTION

this.javascript !== this.java

this.javascript !== self.python

Page 39: Front End Development: The Important Parts

FUNCTIONS :: EXECUTION CONTEXT

Every line of JavaScript code is run in an “execution context.”

ExecCont = {LexicalEnv: {},VarEnv: {},ThisBinding: {}

}

Page 40: Front End Development: The Important Parts

FUNCTIONS :: EXECUTABLE CODE TYPES

● Global code

alert("hello world");● Function code

function callMe () {alert('hello world');

}● Eval code

Page 41: Front End Development: The Important Parts

FUNCTIONS :: GLOBAL CONTEXT

var a = 1,b = 3c = a + b;

alert(c); // 4alert(this); // window

Page 42: Front End Development: The Important Parts

FUNCTIONS :: FUNC CONTEXT :: methodvar a = { b: function() { return this; }};a.b(); //a;a['b'](); //a;var c = {};c.d = a.b;c.d(); //c

Page 43: Front End Development: The Important Parts

FUNCTIONS :: FUNC CONTEXT :: functionfunction a () {

return this;}

var A = a(); // window

Page 44: Front End Development: The Important Parts

FUNCTIONS :: FUNC CONTEXT :: function

var a = { b: function() { return this; }}; var foo = a.b;foo(); //window

Page 45: Front End Development: The Important Parts

FUNCTIONS :: FUNC CONTEXT :: function

var a = { b: function() { var c = function() { return this; }; return c(); }};a.b(); //window

Page 46: Front End Development: The Important Parts

FUNCTIONS :: FUNC CONTEXT :: callfunction t() {

return [].slice.call(arguments, 1);}

var upd = t(1,2,3,4,5); // [2,3,4,5]

fun.call(thisArg[, arg1[, arg2[, ...]]])

Page 47: Front End Development: The Important Parts

FUNCTIONS :: FUNC CONTEXT :: applyfunction t() {

return [].slice.apply(arguments, [1]);}

var upd = t(1,2,3,4,5); // [2,3,4,5]

fun.apply(thisArg[, argsArray])

Page 48: Front End Development: The Important Parts

function Builder () {this.name = 'Arnold';

}

var b = new Builder();// b = {// name: 'Arnold'// }

FUNCTIONS :: FUNC CONTEXT :: new

Page 49: Front End Development: The Important Parts

FUNCTIONS :: FUNC CONTEXT :: referenceExecution Context Syntax of function call Value of this

Global n/a global object (e.g. window)

FunctionMethod call:myObject.foo();

myObject

FunctionBaseless function call:foo();

global object (e.g. window)(undefined in strict mode)

FunctionUsing call:foo.call(context, myArg);

context

FunctionUsing apply:foo.apply(context, [myArgs]);

context

FunctionConstructor with new:var newFoo = new Foo();

the new instance(e.g. newFoo)

Evaluation n/a value of this in parent context

source: http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

Page 50: Front End Development: The Important Parts

TOOLS

Page 51: Front End Development: The Important Parts

REQUIREJS

Page 52: Front End Development: The Important Parts

REQUIREJS :: WHY?

● Web sites are turning into Web apps● Code complexity grows as the site gets

bigger● Assembly gets harder● Developer wants discrete JS files/modules● JavaScript doesn't have import yet

source: http://requirejs.org/docs/why.html

Page 53: Front End Development: The Important Parts

REQUIREJS :: WHAT?

RequireJS is

an AMD JavaScript file and module loader.

Page 54: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine();

Page 55: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine([]);

Page 56: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine(['sandbox', './views/View']);

Page 57: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine(['sandbox', './views/View'], function () {

});

Page 58: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine(['sandbox', './views/View'], function (sandbox, View) {

});

Page 59: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine(['sandbox', './views/View'], function (sandbox, View) { var Module = function () { } return Module;});

Page 60: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine(['sandbox', './views/View'], function (sandbox, View) { var Module = function () { var views = []; this.init = function () { }; this.tickUpdate = function () { } } return Module;});

Page 61: Front End Development: The Important Parts

REQUIREJS :: HOW? :: definedefine(['sandbox', './views/View'], function (sandbox, View) { var Module = function () { var views = []; this.init = function () {}; this.tickUpdate = function () { this.views.push(View.create()); } } return Module;});

Page 62: Front End Development: The Important Parts

REQUIREJS :: HOW? :: configrequire.config({

shim: {'ember': {

deps: ['jquery', 'handlebars'], exports: 'Ember' }

},paths: {

...jquery: 'libs/jquery-1.8.2',tick_mngr: 'managers/tick',ember: 'libs/ember-1.0.0-rc.1',...

}})

Page 63: Front End Development: The Important Parts

JQUERY

Page 64: Front End Development: The Important Parts

JQUERY :: SELECTORS

$(selector).method()

For example, $(‘#list’) will return the elements which has the attribute id=”list”.

For more, see http://api.jquery.com/category/selectors/.

Page 65: Front End Development: The Important Parts

JQUERY :: DOM MANIPULATIONS● $(selector).html()● $(selector).append(html)● $(selector).remove()● $(selector).attr('myAttr', 'value')● $(selector).removeAttr('myAttr')● $(selector).css('width', 40)● $(selector).addClass('my-class')● $(selector).removeClass('my-class')● $(selector).text()● $(selector).val()

Page 66: Front End Development: The Important Parts

JQUERY :: AJAX

$.ajax({ url: ‘/api/posts’ type: ‘POST’, data: {}, success: function () {}, error: function () {}});

Page 67: Front End Development: The Important Parts

JQUERY :: EVENTS● $(selector).click(function () {})● $(selector).dblclick(function () {})● $(selector).mousedown(function () {})● $(selector).mouseup(function () {})● $(selector).mouseover(function () {})● $(selector).mouseenter(function () {})● $(selector).mouseleave(function () {})● $(selector).on(eventName,

function () {})● $(selector).off(eventName,

function () {})

Page 68: Front End Development: The Important Parts

PROMISES

Page 69: Front End Development: The Important Parts

REMINDER :: async naturefunction getData() { var data; $.ajax({ url: 'https://api.github.com/users/bolshchikov', type: 'GET', success: function (response) { data = response; } }); return data;}

var myData = getData(); // ???

http://jsbin.com/imatun/2/edit

Page 70: Front End Development: The Important Parts

REMINDER :: async naturefunction getData() { var data; $.ajax({ url: 'https://api.github.com/users/bolshchikov', type: 'GET', success: function (response) { data = response; } }); return data;}

var myData = getData(); // undefined

http://jsbin.com/imatun/2/edit

Page 71: Front End Development: The Important Parts

TOOLS :: PROMISES :: pyramid of doom

startChannel(function (data) {drawLayout(function () {startFirstModule(function () {...

});});

});

Page 72: Front End Development: The Important Parts

TOOLS :: PROMISES :: parallel

startChannel(function (data) {drawLayout(function () {startFirstModule(function () {...

});});

});

1

1

2

Page 73: Front End Development: The Important Parts

TOOLS :: PROMISES :: defIn computer science, future, promise, and delay refer to constructs used for synchronizing in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete.

The term promise was proposed in 1976 by Daniel P. Friedman and David Wise,[1] [...]

The terms future, promise, and delay are often used interchangeably, although some differences in usage between future and promise are treated below. Setting the value of a future is also called resolving, fulfilling, or binding it.

Source: http://en.wikipedia.org/wiki/Futures_and_promises

Page 74: Front End Development: The Important Parts

source: http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

Page 75: Front End Development: The Important Parts

TOOLS :: PROMISES :: Deferred Object

jQuery.Deferred() A constructor that creates a new Deferred object, can take an optional initFunction parameter that will be called right after the deferred has been constructed.

jQuery.when() A way to execute callback functions based on one or more objects that represent asynchronous tasks.

jQuery.ajax() Performs an asynchronous Ajax requests where the jqXHR objects returned by $.ajax() implement the Promise interface, giving them all the properties, methods, and behaviour of a Promise.

deferred.resolve(arg1, arg2, ...) Resolve a Deferred object and call any 'done' Callback with the given arguments.

deferred.reject(arg1, arg2, ...) Reject a Deferred object and call any 'fail' Callback with the given arguments.

deferred.promise() Returns a promise, that is an immutable view of the deferred object: the promise can be passed around safely since the underlying deferred cannot be resolved or rejected through it.

Page 76: Front End Development: The Important Parts

TOOLS :: PROMISES :: Promise Object

deferred.then(resolveCallback,rejectCallback)

Handlers to be called when the Deferred object is resolved or rejected.

deferred.done() Functions or array of functions that are called when the Deferred object is resolved.

deferred.fail() Functions or array of functions that are called when the Deferred is rejected.

deferred.isResolved Determine whether a Deferred object has been resolved.

Page 77: Front End Development: The Important Parts

TOOLS :: PROMISES :: side 1

$.when(// call functionsstartChannel(),drawLayout()

).done(function () {// do when both are doneinitModule.start();

})

Page 78: Front End Development: The Important Parts

TOOLS :: PROMISES :: side 2function drawLayout () {

var dfd = $.Deferred();function loadSettings() {

// do some ajax request;}function validate() {

... // in case validation faileddfd.reject();

}function render() {

// renderreturn dfd.resolve();

}return dfd.promise();

}

Page 79: Front End Development: The Important Parts

CHROME DEVELOPER

TOOLS

Page 80: Front End Development: The Important Parts

CHROME DEV TOOLS :: OPEN● F12 (Windows)

● Alt + Cmd + i (Mac)

● View > Developer > Developer Tools (Everywhere)

● Mouse right click > Inspect Element (Everywhere)

source: http://www.html5rocks.com/en/tutorials/developertools/part1/

Page 81: Front End Development: The Important Parts

CHROME DEV TOOLS :: TABS

1. Elements: edit HTML, CSS, events

2. Resources: local storage, cookies

3. Network: xhr requests, their size, headers...

4. Source: js editing, debugging, breakpoints

5. Timeline: performance, memory

6. Profile: performance

7. Audits

8. Console

Page 82: Front End Development: The Important Parts

to be continued...

PAUSE