Uma palestra sobre os paradigmas trazidos por bibliotecas e framework como Backbone.js, Angular.js e React. Conheceremos os principais conceitos por trás de programação imperativa, funcional e reativa. Por fim, teremos uma visão clara do quanto evoluímos e o que ainda está por vir na forma e uso da linguagem.
9. <SCRIPT>
var visits = getCookie("counter");
if (visits) {
visits = parseInt(visits) + 1;
document.write("By the way, you have been here " + visits +
" times.");
}
else {
visits = 1;
document.write("By the way, this is your first time here.");
}
setCookie("counter", visits);
</SCRIPT>
http://www.sislands.com/coin70/week7/counter.htm
if e else
10. <SCRIPT>
// Use single-spaced text for Multiplication table
document.write("<CENTER><BLOCKQUOTE><STRONG><PRE><FONT COLOR='FF0000'">)
var i, j, total; // global variables
for (i = 1; i <= 10; i++) {
for (j = 1; j < 10; j++) {
total = i * j;
total = " " + total //add space before each number
// Add another space before single digits
if (total < 10) total = " " + total;
// Display result
document.write(total);
} // end inner j loop
document.write("<BR>"); // end of line break
} // end of i outer loop
document.write("</FONT></PRE></STRONG></BLOCKQUOTE></CENTER>");
</SCRIPT>
http://www.sislands.com/coin70/week2/NestedLoops1.htm
foooorr
21. Todo construtor deve
possuir uma única
responsabilidade
Single responsibility
principle
http://www.infoq.com/br/news/2014/02/solid-principios-javascript
22. Até mesmo as tarefas mais
simples eram complexas
utilizando Web APIs
24. new Ajax.Request('/some_url', {
method:'get',
onSuccess: function(transport) {
var response = transport.responseText
alert("Success! nn" + response)
},
onFailure: function() {
alert('Something went wrong...')
}
})
http://prototypejs.org/learn/introduction-to-ajax
25. getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false
}
Código fonte da versão 1.7.2.0 da Prototype.js
Operação interna
do Request
29. if (!document.getElementsByClassName)
document.getElementsByClassName = function(instanceMethods){
Código fonte da versão 1.7.2.0 da Prototype.js
Object.extend(Function.prototype, (function() {
var ELEMENT_PROTOTYPE = window.HTMLElement ? HTMLElement.prototype :
Element.prototype;
Estender document
Estender construtor de função
Estender objetos do DOM
30. DOM extension is one of the
biggest mistakes Prototype.js has
ever done.
http://perfectionkills.com/whats-wrong-with-extending-the-dom
- Kangax
31. Modificar objetos que não
pertencem ao seu código
não é uma boa prática
https://www.nczonline.net/blog/2010/03/02/maintainable-javascript-
dont-modify-objects-you-down-own
65. var mult = function (a, b) { return a * b }
var negate = _.partial(mult, -1)
var mult2 = _.partial(mult, 2)
var square = function (n) { return n * n }
var result = _.compose(negate, mult2, square)
66. export default store => next => action => {
// [...]
}
https://github.com/rackt/redux/blob/master/examples/real-world/
middleware/api.js
export default function (store) {
return function (next) {
return function (action) {
}
}
}
Portando para ES 5.1
Código original
68. Funções precisam aceitar e
retornar dados imutáveis
// frozen value type
const xy = #[ x, y ]
// functional extension
const xyz = #[ ...xy, z ]
https://github.com/sebmarkbage/ecmascript-immutable-data-structures
69. Mas nem tudo está disponível:
é preciso aprender a esperar
por operações assíncronas
70. getFiles('.', function (files) {
generateIndex(files, function () {
generatePosts(files, ready)
})
})
Funções que geram um blog
71. Programação funcional é
sobre valores e suas
relações
https://blog.jcoglan.com/2013/03/30/callbacks-are-imperative-
promises-are-functional-nodes-biggest-missed-opportunity
73. Promises são valores que
representam o possível
resultado de uma operação
assíncrona
http://tableless.com.br/fluxo-de-execucao-assincrono-em-
javascript-promises
96. var Task = React.createClass({
getInitialState: function () {
return {done: false}
},
render: function () {
return <div onClick={this.change}>
{this.state.done ? 'Ok' : ''}
{this.props.description}</div>
},
change: function () {
this.setState({done: true})
}
})
React.render(<Task description='My task' />,
document.body)
97. var Task = React.createClass({
getInitialState: function () {
return {done: false}
},
render: function () {
return <div onClick={this.change}>
{this.state.done ? 'Ok' : ''}
{this.props.description}</div>
},
change: function () {
this.setState({done: true})
}
})
React.render(<Task description='My task' />,
document.body)
Estado
98. Manipular e manter o histórico
dos estados do DOM é difícil. A
solução é escrever código como
se você recriasse o DOM toda
vez que o estado muda
https://github.com/Matt-Esch/virtual-dom
99. Já existe um esquema
gratuito para o fluxo dos
dados: O DOM
http://www.code-experience.com/why-you-might-not-need-mvc-with-
reactjs/
(os eventos e CSS já utilizam)
119. FRP é sobre relações
dependentes que se estabilizam
com o passar do tempo
https://www.zweitag.de/en/blog/technology/functional-reactive-
programming-frp