Saltar al contenido principal
FRONT END DEVELOPMENT
by Sergey N. Bolshchikov
The Important Parts
3 hours of
wasting my time?
Let's find out
LET'S FIND OUT
1. Is it possible to do shadows with CSS?
LET'S FIND OUT
1. Is it possible to do shadows with CSS?
2. Who can write such function?
var result = addNumbers(2)(3);
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"?
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?
OUTLINE
I. CSS
1. Basics
2. CSS3
3. LESS
II. JavaScript
1. Functions: objects
2. Lexical scope: closures, module pattern
3. Execution contexts and "this" value
III. Tools and Libraries
1. RequireJS
2. jQuery
3. Promises
4. Chrome Dev Tools
CSS
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:link
E: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:link
a:visited
CSS :: SELECTORS (cont.)
Selector Description Example
E:active
E:hover
E:focus
Matches E during certain user
actions.
a:active
a:hover
a: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
CSS :: BOX MODEL
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
CSS :: CSS3
● border-radius
● box-shadow
● gradients
● multiple columns
● transformations
● animation
http://jsbin.com/udimij/1/edit
LESS
LESS :: WHY?
● CSS is too much writing
.nav {}
.nav ul {}
.nav ul li {}
● No validation
● Declarative
LESS :: WHAT?
LESS extends CSS with dynamic behavior
such as variables, mixins, operations and
functions.
LESS :: NESTING
.nav {
ul {
...
li {
...
}
}
}
LESS :: VARIABLES
@color: #4D926F;
#header {
color: @color;
}
h2 {
color: @color;
}
#header {
color: #4D926F;
}
h2 {
color: #4D926F;
}
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;
}
FUNCTIONS
in
JAVASCRIPT
FUNCTION
is an
OBJECT
FUNCTIONS :: OBJECTS
function foo (x) {
return x + 1;
}
function bar (y) {
return y * 2;
}
var myFuncs = [foo, bar];
myFuncs[0](2) // 3
FUNCTIONS :: OBJECTS
var callFirst = function (x) {
return x + 1;
}
var callSecond = function (f, x) {
return f(f(x));
}
var attempt = callSecond(callFirst, 2); // 4
FUNCTIONS :: OBJECTS
var makeFunc = function () {
var addOne = function (x) {
return x + 1;
}
return addOne;
}
var f = makeFunc();
f(3); // 4
LEXICAL
ENVIRONMENT
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.
FUNCTIONS :: LEXICAL ENV :: wtf
function () {
...
function () {
...
return;
}
return ;
}
Lexical Env Outers
Lexical Env Inner
FUNCTIONS :: LEXICAL ENV :: nesting
function createIncreaser () {
var accumulator = 0;
var increaser = function () {
return accumulator += 2;
};
return increaser;
}
var inc = createIncreaser();
console.log(inc()); // 2
console.log(inc()); // 4
console.log(inc()); // 6
FUNCTIONS :: LEXICAL ENV :: closure
function createIncreaser () {
var accumulator = 0;
var increaser = function () {
return accumulator += 2;
};
return increaser;
}
var inc = createIncreaser();
console.log(inc()); // 2
console.log(inc()); // 4
console.log(inc()); // 6
env
code block
FUNCTIONS :: LEXICAL ENV :: module pattern
// not a constructor
var myModule = (function (projId) {
var moduleName, projectorId;
moduleName = 'toolbar';
projectorId = projId;
return {
init: function () {
console.log(moduleName);
},
tickUpdate: function () {}
};
})();
myModule.init() // "toolbar"
myModule.moduleName // undefined
PROBLEM
<div>
I am div 1
</div>
<div>
I am div 2
</div>
<div>
I am div 3
</div>
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
PROBLEM
environment
var i
event
handler 1
event
handler 2
event
handler 3
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
PROBLEM
environment
event
handler 1
event
handler 2
event
handler 3
var i var i var i
EXECUTION
CONTEXT
FUNCTIONS :: EXECUTION
this.javascript !== this.java
this.javascript !== self.python
FUNCTIONS :: EXECUTION CONTEXT
Every line of JavaScript code is run in an
“execution context.”
ExecCont = {
LexicalEnv: {},
VarEnv: {},
ThisBinding: {}
}
FUNCTIONS :: EXECUTABLE CODE TYPES
● Global code
alert("hello world");
● Function code
function callMe () {
alert('hello world');
}
● Eval code
FUNCTIONS :: GLOBAL CONTEXT
var a = 1,
b = 3
c = a + b;
alert(c); // 4
alert(this); // window
FUNCTIONS :: FUNC CONTEXT :: method
var a = {
b: function() {
return this;
}
};
a.b(); //a;
a['b'](); //a;
var c = {};
c.d = a.b;
c.d(); //c
FUNCTIONS :: FUNC CONTEXT :: function
function a () {
return this;
}
var A = a(); // window
FUNCTIONS :: FUNC CONTEXT :: function
var a = {
b: function() {
return this;
}
};
var foo = a.b;
foo(); //window
FUNCTIONS :: FUNC CONTEXT :: function
var a = {
b: function() {
var c = function() {
return this;
};
return c();
}
};
a.b(); //window
FUNCTIONS :: FUNC CONTEXT :: call
function t() {
return [].slice.call(arguments, 1);
}
var upd = t(1,2,3,4,5);
// [2,3,4,5]
fun.call(thisArg[, arg1[, arg2[, ...]]])
FUNCTIONS :: FUNC CONTEXT :: apply
function t() {
return [].slice.apply(arguments, [1]);
}
var upd = t(1,2,3,4,5);
// [2,3,4,5]
fun.apply(thisArg[, argsArray])
function Builder () {
this.name = 'Arnold';
}
var b = new Builder();
// b = {
// name: 'Arnold'
// }
FUNCTIONS :: FUNC CONTEXT :: new
FUNCTIONS :: FUNC CONTEXT :: reference
Execution Context Syntax of function call Value of this
Global n/a global object (e.g. window)
Function
Method call:
myObject.foo();
myObject
Function
Baseless function call:
foo();
global object (e.g. window)
(undefined in strict mode)
Function
Using call:
foo.call(context, myArg);
context
Function
Using apply:
foo.apply(context, [myArgs]);
context
Function
Constructor 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/
TOOLS
REQUIREJS
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
REQUIREJS :: WHAT?
RequireJS
is
an AMD JavaScript file
and module loader.
REQUIREJS :: HOW? :: define
define();
REQUIREJS :: HOW? :: define
define([]);
REQUIREJS :: HOW? :: define
define(['sandbox', './views/View']);
REQUIREJS :: HOW? :: define
define(['sandbox', './views/View'],
function () {
});
REQUIREJS :: HOW? :: define
define(['sandbox', './views/View'],
function (sandbox, View) {
});
REQUIREJS :: HOW? :: define
define(['sandbox', './views/View'],
function (sandbox, View) {
var Module = function () { }
return Module;
});
REQUIREJS :: HOW? :: define
define(['sandbox', './views/View'],
function (sandbox, View) {
var Module = function () {
var views = [];
this.init = function () { };
this.tickUpdate = function () { }
}
return Module;
});
REQUIREJS :: HOW? :: define
define(['sandbox', './views/View'],
function (sandbox, View) {
var Module = function () {
var views = [];
this.init = function () {};
this.tickUpdate = function () {
this.views.push(View.create());
}
}
return Module;
});
REQUIREJS :: HOW? :: config
require.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',
...
}
})
JQUERY
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/.
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()
JQUERY :: AJAX
$.ajax({
url: ‘/api/posts’
type: ‘POST’,
data: {},
success: function () {},
error: function () {}
});
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 () {})
PROMISES
REMINDER :: async nature
function 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
REMINDER :: async nature
function 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
TOOLS :: PROMISES :: pyramid of doom
startChannel(function (data) {
drawLayout(function () {
startFirstModule(function () {
...
});
});
});
TOOLS :: PROMISES :: parallel
startChannel(function (data) {
drawLayout(function () {
startFirstModule(function () {
...
});
});
});
1
1
2
TOOLS :: PROMISES :: def
In 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
source: http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics
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.
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.
TOOLS :: PROMISES :: side 1
$.when(
// call functions
startChannel(),
drawLayout()
).done(function () {
// do when both are done
initModule.start();
})
TOOLS :: PROMISES :: side 2
function drawLayout () {
var dfd = $.Deferred();
function loadSettings() {
// do some ajax request;
}
function validate() {
...
// in case validation failed
dfd.reject();
}
function render() {
// render
return dfd.resolve();
}
return dfd.promise();
}
CHROME
DEVELOPER
TOOLS
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/
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
to be continued...
PAUSE