Talk: JavaScript can do WHAT?!
These are the notes for a talk I give. Slides are here. It was originally presented at Port80 Perth - 2016 February Meetup which can be Watched Here.
An overview of the latest capabilities from the JavaScript Web Development scene. includes overviews of the benefits and when to use, for the following:
Suitable for beginners and professionals. Will describe each section, and touch on basic examples. Depth is available on questions.
JavaScript and the DOM were still very basic, with many browser inconsistencies. JavaScript was not the only player, VBScript and JScript were also possible. CSS was still emerging and required evanglisism. JavaScript was used almost exclusively for mere form validation and alerts/prompts. Think of your typical email form validation.
<form action="" method="post" onsubmit="return confirm('Are you sure?')">
JavaScript became consistent, however features across browsers were still inconsistent. In 1999 and the years following, different browsers provided JavaScript access to server-side communication via the XHR/XMLHttpRequest/AJAX standard. This was primarily used at the time for consolidating form validation to the server-side, for consistent and secure validation. Think of your typical yet simple government form validation.
var request = new XMLHttpRequest()
request.onreadystatechange = function () {
if (this.readyState === 4) {
var result = JSON.parse(request.responseText)
if ( !result.success ) {
throw new Error(result.message || 'Validation of the form failed')
}
}
}
In later years, this technology would be used for polling to emulate Web Socket technology for server to client notifications and communication.
In this time, JavaScript was becoming necessary to accomplish more advanced browser functions, such as form validation, page interactions, and animations. Think of JavaScript's usage in early WordPress versions.
In early 2005, Prototype.js came out, accomplishing Object Orientated techniques, notably by monkey-patching native classes. In mid 2005, Scriptaculous. came out, accomplishing visual animations and interactions. Example..
document.getElementById('myel').style.color = 'red'
document.getElementById('myel').setStyle({color: 'green'})
$('myel').setStyle({color: 'white'})
In late 2006, MooTools came out, accomplishing Object Orientated techniques, notably by new class types.
var Animal = new Class({
initialize: function(name) {
this.name = name;
}
})
var Cat = new Class({
Extends: Animal,
talk: function() {
return 'Meow!';
}
})
var Dog = new Class({
Extends: Animal,
talk: function() {
return 'Arf! Arf';
}
})
var animals = {
a: new Cat('Missy'),
b: new Cat('Mr. Bojangles'),
c: new Dog('Lassie')
}
Object.each(animals, function (animal) {
alert(animal.name + ': ' + animal.talk())
})
In late 2006, jQuery came out, accomplishing Object Orientated techniques, notably by simplistic chaining and beginner friendly API - OO without thinking about it. In late 2007, jQuery UI came out, accomplishing visual animations and interactions via widgets.
$.prototype.log = function () {
var $el = this
alert($el.html())
}
$('p.surprise').addClass('ohmy').show('slow').log()
In early 2008, John Resig (author of jQuery) published Simple JavaScript Inheritance, a 25 line utility that effectively emulated proper classes in JavaScript.
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing
},
dance: function(){
return this.dancing
}
});
var Ninja = Person.extend({
init: function(){
this._super(false)
},
dance: function(){
// Call the inherited version of dance()
return this._super()
},
swingSword: function(){
return true
}
});
var p = new Person(true)
p.dance() // => true
var n = new Ninja()
n.dance() // => false
n.swingSword() // => true
// Should all be true
p instanceof Person && p instanceof Class &&
n instanceof Ninja && n instanceof Person && n instanceof Class
In this time, JavaScript was also seeing use in early Content Management Systems, requiring page transitions and state management. Think of your typical multi-part form submission flow.
In 2008, window.onhashchange
came out in some browsers (with others following), accomplishing the first unintended browser-supported way of accomplishing state management inside web browsers:
Example.
window.location.onhashchange = function () {
alert('hash:', window.location.hash)
}
window.location.hash = 'one' // alerts "hash: one"
window.location.hash = 'two' // alerts "hash: two"
history.back() // alerts "hash: one"
In 2011, window.onpopstate
came out in some browsers (with others following), accomplishing the first intended browser-supported way of accomplishing state management inside web browsers:
window.location.onpopstate = function () {
alert('location: ' + document.location.href + ', and the state has changed to: ' + JSON.stringify(event.state))
}
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null
history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}
In this time, JavaScript was seeing good cross-browser consistency (for the most part), advanced server-side backends, and the emergency of Client-Side Web Applications. Think of your typical Facebook commenting workflow.
In 2008, client-side templating engines started to come out, accomplishing server-side style templating on the client-side. There would later go on to become very popular.
<div class="smarty">
{$myvar|default:"hi"|capitalize}
{assign var="myvar" value="hello"}
{$myvar|default:"hi"|capitalize}
</div>
<script>$('.smarty').populate()</script>
In late 2010, Backbone came out, accomplishing organised Client-Side Web Applications, notably by the MVC pattern.
var MessageList = Backbone.View.extend({
initialize: function() {
var messages = this.collection
messages.on("reset", this.render, this)
messages.on("add", this.addMessage, this)
messages.on("remove", this.removeMessage, this)
messsages.each(this.addMessage, this)
}
})
// Later, in the app...
Inbox.messages.add(newMessage);
In 2012, other client-side application libraries reached maturity, such as Angular and Ember, and the TodoMVC project was created.
var TodoList = React.createClass({
render: function () {
var createItem = function (item) {
return <li key={item.id}>{item.text}</li>
}
return <ul>{this.props.items.map(createItem)}</ul>
}
})
var TodoApp = React.createClass({
getInitialState: function () {
return {items: [], text: ''}
},
onChange: function (e) {
this.setState({text: e.target.value})
},
handleSubmit: function (e) {
e.preventDefault()
var nextItems = this.state.items.concat([{
text: this.state.text, id: Date.now()
}])
var nextText = ''
this.setState({items: nextItems, text: nextText})
},
render: function () {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.onChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
)
}
})
ReactDOM.render(<TodoApp />, mountNode)
In 2010, Node.js began public adoption, accomplishing server-side and desktop style applications with JavaScript, notably with C style capabilities. This unleashed JavaScript from the web browser and allowing code for the first notable time to be shared between the client and server.
var http = require('http'), hostname = '127.0.0.1', port = 1337
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello World\n')
}).listen(port, hostname, function () {
console.log('Server running at http://' + hostname + ':' + port + '/');
});
In 2012, npm began public adoption with its bundling with node 0.6.13, accomplishing standardised JavaScript sharing for the first time.
mkdir multiply
npm init
echo "module.exports = function (a, b) { return a*b }" > index.js
npm publish
mkdir multiplier
npm init
npm install --save multiply
echo "console.log(require('multiply')(5, 10))" > index.js
node index.js
Browserify, Gulp, Grunt, Mocha, PhantomJS, DocPad, Yeoman, Babel, ChainyJS, npm scripts.
http://johnny-five.io http://www.nodecopter.com