Post on 06-May-2015
description
JavaScript for Web Developer
ZUBZIB BLACK COFFEE #8
CHALERMPON AREEPONG (NINE)
AGENDA Basic Programming
Object Oriented Programming
3rd JavaScript Libraries
AJAX, JSON, Handle Event
Debugging
Unit Test
MVC
JavaScript (JS) Created in 1995 by Brendan Eich
Name: Mocha in LAB, LiveScript for Netscape Navigator 2.0 and last rename to JavaScript with Netscape 2 beta in December 1995
Microsoft add JavaScript to IE in 1996 called JScript
Brendan Eich
Stuff You Should Know JavaScript run in Web Browser
JavaScript integrate with DOM
JavaScript is a dynamic type
Current JavaScript complied to ECMA-262 version 5.1 http://en.wikipedia.org/wiki/ECMAScript
JavaScript no coding standard, has only Best Practice
JavaScript IDE Tools Web Browser Developer Tool
◦ Chrome (F12)◦ Firefox add-in Firebug (F12)◦ IE (F12)◦ Safari◦ Others
JavaScript IDE Tools IDE Setup
◦ Visual Studio◦ WebMatrix◦ Kineticwing◦ WebStrom◦ CodeMirror◦ Other http://
en.wikipedia.org/wiki/Comparison_of_JavaScript-based_source_code_editors
Cloud IDE
◦ Cloud9◦ CodeAnywhere◦ Cloud IDE◦ Sourcekit◦ Codepen, jsfiddle, jsbin◦ Other http
://www.hongkiat.com/blog/cloud-ide-developers/
Demo tool Chrome
jsfiddle
Visual Studio 2012 Update 3
Resharper 8
JavaScript Basic Programming Declare Variable
var testString = 'ASP.NET & MVC Developers Thailand';var testInt = 2000;var testBool = true;var testDouble = 2000.2334;var testReg = /(?:.d){2}/;var testUndefined;var testNull = null;var testArray = new [0, 1, 2, 3];var testObj = new {};var testFunc = new function () { };
JavaScript Basic Programming Declare Function
//Declare functionfunction MVCShowOff() { return "Hi there, we are X!!"; }var message = MVCShowOff(); //call
//Declare varriable functionvar MvcShowOff = function () { return "Hi there, we are X!!"; };message = MvcShowOff(); //call
//Declare Self-Invoking function(function () { return "Hi there, we are X!!"; })();//<-- (); is a caller
//Declare Annonymous Functiondocument.onload = function (e) { alert("Hi there, we are X!!"); };
JavaScript Basic Programming Parameter Function
//Declare Function with parameterfunction Mid2Vals(hi, low) { return (hi + low) / 2; }var result = Mid2Vals(5, 10);
//Declare Function without parameter and use arguments parameterfunction Mid2Vals() { return (arguments[0] + arguments[1]) / 2; }var result = Mid2Vals(5, 10);
JavaScript Basic Programming Class and Object
//1. Declare Object Type, Classfunction MvcMember() { this.name = "Nine not K9"; this.isInstuctor = true;};
//Declare varriable and callvar mrNine = new MvcMember();alert(mrNine.isInstuctor); // true
//2. Declare Object literalvar mrNine = { name : "Nine not K9", isInstuctor : true};
//Callalert(mrNine.isInstuctor); // true
JavaScript Basic Programming Complex Class Object
//1. Declare Class function MvcMember() { this.name = "Nine not K9"; this.isInstuctor = true; this.event = new function Event() { this.name = "Zubzib Black Coffee #5 Update Skills v1"; this.session = new function Session() { this.name = "JavaScript for Web Developer"; this.audiences = 40; }; this.place = "University of Thai Chamber of Commerce"; this.location = new function Location() { this.lat = 13.779276; this.long = 100.560326; this.getGeoLocation = lat + ', ' + long; };};};
//2. Initial varriable and access datavar mrNine = new MvcMember();alert(mrNine.event.name);alert(mrNine.event.session.name);alert(mrNine.event.location.getGeoLocation);
JavaScript Basic Programming Late Declare Variable and Function
//1. Declare Class function MvcMember() { this.name = "Nine not K9"; this.isInstuctor = true;};
//And initial an objectvar mrNine = new MvcMember();
//2. late declare variablemrNine.say = "Hi everybody"; // mrNine["say"] = "Hi everybody"; //same
//3. late declare functionmrNine.thinkAbout = function (source) { return "I'm thinking about the " + source; };
JavaScript Basic Programming Condition, Loop, try… catch
//IF Else conditionvar x = 0, y = 1;if (x == 1) { alert('Yes'); }else { alert('No'); }
//Switch Conditionvar word = "Hi";switch (word) { case "Hi": alert('How r u?'); default: alert("Hey what's was wrong with you?");}
//While loopvar x = 5;while (x<1) { x--; }alert(x);
//For loopvar title = "JavaScript".split('');for (var i = 0; i < title.length; i++) { alert(title[i]);}
JavaScript Basic Programming Condition, Loop, try… catch
// For Each Loopvar topic = "JavaScript very easy".split(' ');topic.forEach(function(word) { alert(word); });
//try catch blocktry { var x; x.ErrorPlease();} catch(e) { alert("catch error : " + e.message);}
JavaScript Basic Programming Comparisons 1
// Assigh valuevar x = 10;console.log("x="+x);
//Comparisonvar a = "test", b = "TEST";var result = a == b;console.log("comparison a == b ? "+result);
//Identityvar identityResult = a === x;console.log("identity a is b ? " + identityResult);
JavaScript Basic Programming Comparison 2
//check base type and value typevar undef;var num = 90;var str = "Test";var bool = true;var func = function (a, b) { return a + b; };var object = { x: 500 };var arr = ["Nine", "Non", "Tape"];
console.log(typeof undef); //"undefined"console.log(typeof num); //"number"console.log(typeof str); //"string"console.log(typeof bool); //"boolean"console.log(typeof func); //"function"console.log(typeof object); // "object"console.log(typeof arr); // "object"
//check object instance of classvar arr = ["Nine", "Non", "Tape"];console.log(arr instanceof Array); // true
function Speaker() { this.name = "Nine"; }var mrNine = new Speaker();console.log(mrNine instanceof Speaker); // true
JavaScript Basic Programming Value of variables are always false in condition
var a = null;var b; // undefinedvar c = 0;var d = false;var e = "";
if (a) // falseif (b) // falseif (c) // falseif (d) // falseif (e) // false
JavaScript Basic Programming Inheritance with Prototype
function Speaker(isSpeaking) { this.isSpeaking = isSpeaking == null ? false : isSpeaking; }
Speaker.prototype.say = function () {return "Break session"; };
function ZZSpeaker () { this.isEating = true; }
ZZSpeaker.prototype = new Speaker();ZZSpeaker.prototype.sleepyShow = function () { alert('wake up !!!'); };ZZSpeaker.prototype.say = function () { return "Ask me please.."; };
var nineSpeak = new ZZSpeaker();nineSpeak.say();nineSpeak.sleepyShow();
3rd JavaScript Framework and Library
jQuery is a library created on top JavaScript, to help us access DOM and populate HTML element, content , CSS, animation and DOM Event
The two thinks jQuery dose
1. SELECT elements or a group of element by CSS Selector
2. Take Action on elements
3rd JavaScript Framework and Library
jQuery : Get Started<!DOCTYPE html><html><head> <title></title></head><body> <div class="test"></div> <!-- 1. Add script reference to local or CDN --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> //2. declare document ready $(document).ready(function () { $('div.test').html("<h1>JavaScript for web developer</h1>"); }); </script></body></html>
3rd JavaScript Framework and Library
jQuery : query and action
<div class="test"></div> <input id="btnShowMessage" type="button" value="click me" />
//2. declare document ready $(document).ready(function () { //3. Bind Element Action to custom function $('#btnShowMessage').click(function () { $('div.test').html("<h1>DOM Ready binding event</h1>"); }); }); //4. Early binding event can declare out of DOM Ready block $('#btnShowMessage').on('click', function () { $('div.test').html("<h1>Early binding event</h1>"); });
AJAX ????
AJAX: Asynchronous JavaScript and XML
None blocking user action and no screen freeze
Use AJAX (native code)// This is the client-side script// Initialize the Ajax requestvar xhr = XMLHttpRequest();xhr.open('get', 'http://google.com');// Track the state changes of the requestxhr.onreadystatechange = function () { // Ready state 4 means the request is done if (xhr.readyState === 4) { // 200 is a successful return if (xhr.status === 200) { alert(xhr.responseText); // 'This is the returned text.' } else { alert('Error: ' + xhr.status); // An error occurred during the request } }}// Send the request to send-ajax-data.phpxhr.send(null);
Use AJAX with JQUERY $.get()
$.post()
$.getJSON()
$.ajax()
Demo
$.get('ajax/test.html', function (data) { $('.result').html(data); alert('Load was performed.');});
$.post('ajax/test.html', function (data) { $('.result').html(data);});
$.getJSON('ajax/test.json', function (data) { var items = []; $.each(data, function (key, val) { items.push('<li id="' + key + '">' + val + '</li>'); });});
JSON ????
JSON : JavaScript Object Notation
JSON is a text-based open standard designed for human-readable data interchange
//JavaScript Objectvar session = { name: 'Nine', sessionName: 'JavaScript for Web Developer', };
//JSON Object{"name": "Nine", "sessionName" : "JavaScript for Web Developer" }
JSON JavaScript Object to JSON
var session = { name: $('input#name').val(), sessionName: $('input#sesseionName').val() };
//convert to json var json = JSON.stringify(session);
JSON Demo JSON
Debug JavaScript JavaScript Debugger Tools
1. Browser Web Developer Tools (F12)
2. Visual Studio 2012 + IE10 or later
Debug JavaScriptPut break point and click html button
JavaScript Unit Testing article
MVC power by AngularJSarticle