javascript!

24
JavaScript!

Upload: rtigger

Post on 10-May-2015

924 views

Category:

Technology


0 download

DESCRIPTION

The pros and cons of JavaScript as a language, as well as a few libraries that make JavaScript and web development awesome.

TRANSCRIPT

Page 1: JavaScript!

JavaScript!

Page 2: JavaScript!

JavaScript v1• Main features: handle browser events (load, mouse, etc.) and

navigate and manipulate the web page document• Primary original use was for image swapping on mouse events

and basic form validation• Browser rendering engines were too underpowered to do

anything cool with it• Inconsistent implementations between browsers• Netscape 3 (who made it) was a full version ahead of IE 3

Page 3: JavaScript!

JavaScript v1• Most “serious” developers hated it• No IDE• No debugging tools• Security flaws• Marketed as “JavaScript for dummies”• Mostly used by web designers copy-paste-ing code

Page 4: JavaScript!

Browser v4• Netscape and IE 4 introduce completely separate

implementations of Dynamic HTML / Document Object Model• Libraries were created to make Netscape code work in IE and

vice versa• Lowest common denominator was too low to accomplish

anything

Page 5: JavaScript!

Browser v4• Two side effects:• Netscape died to give way to Mozilla, but it was years before

Mozilla had a stable release, allowing IE to dominate market share

• Flash was really the only consistent platform to do anything cool

Page 6: JavaScript!

My Favourite JavaScript Quote

“Anyway I know only one programming language worse than C and that is JavaScript. [...] the net result is that the programming-vacuum filled itself with the most horrible kluge in the history of computing: JavaScript.”- Robert Cailliau

Page 7: JavaScript!

Enter AJAX• Most devs more or less ignored JavaScript as a useful language

until AJAX came along• AJAX suddenly enabled great user experiences on web pages

by loading data / html / scripts after the initial page load, not requiring a browser refresh between actions

• A number of cross-browser AJAX frameworks emerged that also enabled other cross-browser functionality• Prototype, jQuery, MooTools, Dojo, etc.

• Debugging tools created (firebug, dev console), better support in IDEs, browser rendering more powerful

• All in all, JavaScript is good now (or at least better)

Page 8: JavaScript!

JavaScript – Functions• Functions are objects• Have their own properties and methods (length, call, etc.)• Can be assigned to variables• Can be passed as arguments• Can be returned by other functions• Can be nested, maintaining scope (see: closure)

Page 9: JavaScript!

JavaScript – Objects• Prototype-based Objects• Every object has a “prototype” property that references another

object• Prototype is only used for retrieval

• If our object doesn’t have the requested property, it’ll check its prototype (and its prototype, and its prototype, and so on…)

• Prototypes are dynamic • editing a prototype means all of its objects are affected, regardless of

when they were created

Page 10: JavaScript!

JavaScript – Literal Notation• Easy inline way to declare objects and arrays• aka JSON• Object: { Property: Value }• Array: [1, 2, 3]• Object Array: [{Property: Value}, {Property: Value}]

Page 11: JavaScript!

JavaScript – Scope• Scope• Scope in JavaScript is controlled by Functions, not Blocks• Variables declared outside of a function / object (or without var)

are automatically Global• Can lead to terrible conflicts between scripts

• Context (this)• “this” refers to the owner of the function being called• Anonymous functions are owned by Global (window)• Event handlers are owned by the control firing the event

(sometimes)

Page 12: JavaScript!

JavaScript• Bad Stuff• Global Variables by default• Lack of language-defined modules / namespaces• No standard for distributing code across files• Pretty small core library• All numbers are binary floating points

• Makes bitwise operators REALLY inefficient• NaN

• typeof NaN === ‘number’ //true• NaN === NaN //false

• 0, NaN, ‘’, false, null, and undefined all evaluate to false• == behaves differently from ===• No real way to “protect” source code / IP• Still some browser-specific inconsistencies

• *cough* Internet Explorer *cough*

Page 13: JavaScript!

jQuery• DOM selection using selector syntax• DOM traversal and modification• Event binding and delegation• CSS manipulation• AJAX• Extensibility• Cross-browser support

Page 14: JavaScript!

jQuery - Selectors

Pre-jQuery

var classElements = new Array();function getElementsByClassName(className, element) { if(element.className == className) { classElements.push(element); } for(var node in element.childNodes) { getElementsByClassName( className, node); }}getElementsByClassName(“sadPanda”, document.body);

jQuery

var classElements = $(“.happyCat”);

jQuery selectors are AWESOME.

Page 15: JavaScript!

jQuery - Selectors:animated

[alt=“backgroundImage”]

:button:checked

table > tr

.className:contains(“Hello”)

:even

:first-child:gt(5)

#playlistTable

:last

td.name + td.address

:parent

:visible

“#playlistTable td.name:odd > img[alt|=“chad”]:visible”

Page 16: JavaScript!

jQuery - Manipulation• Allows reading, editing, insertion, deletion, and replication of

elements and attributes in the document

• $(‘#playlistTable’).append(“<div>Hello</div>”)

• $(‘.userRow’).addClass(‘selected’);

• $(‘#accountTable tr’).detach();• See also: $(‘#accountTable’).empty();

• $(‘#errorMessage’).html(“<b>I didn’t say Simon Says</b>”);

• $(‘#errorMessage’).css(‘color’, ‘red’);

• $(‘#errorMessage’).css(‘color’); //returns ‘red’

• $(‘input:text’).val(“I HAVE TAKEN OVER YOUR FORM”);

Page 17: JavaScript!

jQuery - Events• Register functions to handle when the browser (or other code)

triggers an event• $(‘input:button’).bind(‘click’, function() { alert(“CLICK.”); });• $(‘div.hoverable’).delegate(‘mouseover’, handleHoverEvent);• $(document).ready(pageLoad);

Page 18: JavaScript!

jQuery - AJAX• Make requests to the server for data / HTML / JavaScript

without refreshing the page• get(“/products”, onProductsLoaded);• $(‘#widgetDialog’).load(“/widgets/editProduct”);• var formData = $(‘form’).serialize(); post(“/saveProduct”, formdata, onProductSaved);

Page 19: JavaScript!

jQuery - Extensibility• Hundreds of jQuery plugins

Page 20: JavaScript!

jQuery Templates• Sends a template of how data should be represented with the

page, then sends the data to fill that template with

Page 21: JavaScript!

Backbone.js• Client-side JavaScript MVC framework• Models with custom events• Collections with enumerable functions• Views with declarative event handling• Integrates with RESTful JSON web services

Page 22: JavaScript!

Backbone - Collections• Represents a group of models• Maps to a REST endpoint• /products

• Collection.fetch – calls REST endpoint, parses result, creates model objects, adds to collection

• Fires “refresh”, “add”, “remove”, “change” events• Provides enumeration functions over models (foreach, find,

map, max, min, sort, indexof, etc)

Page 23: JavaScript!

Backbone - Models• Represents the data from the server as a property bag• Model.get(“property”), Model.set({Property: “value”})

• Provides methods to interact with REST service• Fetch, save, destroy

• Provides validation• Fires events (“changed”)

Page 24: JavaScript!

Backbone - Views• Represents the view of a model or a control on a page• More of a ViewModel than a true View

• Tied to a root element in the page (View.el)• Responds to events on its model or collection• this.model.bind(‘change’, this.render);

• Declarative Events{ “click .icon”: “open” }

• Use in conjunction with jQuery• this.$(‘.selector’) === $(‘.selector’, this.el)