SlideShare a Scribd company logo
1 of 29
Client Side Programming 2
Web Information Systems - 2015
Advanced Javascript
Let’s take this a step further
1
Advanced Javascript
Function Prototypes
● Every JavaScript object has a
prototype.
● The prototype is also an object.
● All JavaScript objects inherit their
properties and methods from their
prototype.
src: w3schools
Advanced Javascript
Object Constructor
function person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
var me = new person(“jeremy”, “Brunn”, 34)
src: w3schools
Advanced Javascript
Add a property
● me.favoriteFood = “pizza”
Add a property to a prototype
● person.favoriteFood = “”
Add a method
● me.getName = function() {
return firstName+”“+lastName;
}
src: w3schools
Advanced Javascript
Adding to constructors
function person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.getName = function() {
return firstName+”
“+lastName;
}
src: w3schools
Advanced Javascript
Adding via prototype
person.prototype.getName = function() {
return this.firstName+” “+this.lastName;
}
person.prototype.setFaveFood =
function(food) {
this.favoriteFood = food;
} src: w3schools
Advanced Javascript
Ajax and Callbacks
Asynchronous Javascript and XML
● data to/from the server side
$.ajax({
url: “http://www.someServer.com”
}).done(success_callback)
.fail(fail_callback)
.always(always_callback)
Advanced Javascript
Callbacks
● functions passed to other functions as
arguments.
In the previous example, success_callback
references a function that will be called when
the ajax request completes successfully;
otherwise, the function referenced by
fail_callback will be called. No matter what,
always_callback will be called.
Advanced Javascript
Special Considerations
When requesting data from another domain,
it will probably be necessary to add {
dataType: “jsonp” } to the ajax argument
object.
● Same-origin Policy
● Cross-origin resource sharing
Also, you can’t make an ajax call to your
local computer's file system, you’ll need a
local server running to test.
Advanced Javascript
Javascript Aids
These help clean code and suggest
corrections to problems before they arise.
● JSLint
● JSHint - I prefer this one. It’s not quite so
restrictive.
src: w3schools
Advanced Libraries
Doing more with less
2
Javascript Libraries
Previously, we looked at accessing
elements on the DOM with JQuery.
Now we’ll examine some other things
that we can do with Javascript through
JQuery and other libraries.
Javascript Libraries
DOM Event listeners in JQuery
$(“#submit”).click(function(e){
// do something
})
is shorthand for
$(document).on.(“click”, “#submit”,
function(e){
// do something
})
Javascript Libraries
DOM Event listeners in JQuery
$(“#submit”).click(function(e){
// e is the event to handle
e.preventDefault();
e.stopPropagation();
targetElement = e.currentTarget;
var id = targetElement.id;
// id = “submit”
})
Javascript Libraries
Common Events
◦ click - an element is clicked
◦ dblclick - an element is dbl clicked
◦ focus - an element gets focus
◦ change - an element’s value changes
▫ <input>, <textarea>, or <select>
◦ hover - an element is hovered over
◦ keydown - user presses a key on
keyboard
◦ keyup - user releases a key on the
keyboard
Javascript Libraries
Programmatically Triggering Events
$(“#submit”).trigger(“click”);
Javascript Libraries
Iterating elements in JQuery
var liArray = [];
$(“ul#myList > li”).each( function(i) {
liArray.push( $(this).text() );
// add the li text (string) to the array
// this is the current element
// i is the index
});
Javascript Libraries
Iterating in JQuery (and appending el)
var numArray = [ 1, 2, 3, 4, 5 ];
$.each(numArray, function(index, value) {
$(“#myList”).append($(“<li>”).text(value));
// adds lis to the ul “#myList”
});
Javascript Libraries
Underscore
An awesome library for accessing data,
and much more...
instead of JQuery’s “$”, use “_”
First, a comparison.
Javascript Libraries
Iterating lists in underscore
var numArray = [ 1, 2, 3, 4 ];
_.each(numArray, function(value, index) {
$(“#myUL”).append($(“<li>”).text(value));
// adds lis to the ul “#myUL”
});
Notice “value” and “index” are reversed
Also, you cannot break from _.each()
Javascript Libraries
Iterating objects in undescore
var numObj = { a: 1, b: 2, c: 3, d: 4 };
_.each(numObj, function(value, key) {
$(“#myUL”).append(
$(“<li>”).text(key+” : “+value));
// adds lis to the ul “#myUL”
});
Javascript Libraries
Some more examples using this list of
people objects.
var peopleList = [
{ name: ”Jeremy”, role: “student” },
{ name: ”Tanvi”, role: “instructor”
},
{ name: ”Pavan”, role: “student” },
{ name: “Pramod”, role: “student” }
];
Javascript Libraries
_.pluck(numObj, “name”);
// [“Jeremy”, ”Tanvi”, “Pavan”, “Pramod”]
_.where(numObj, { role: “instructor”});
// [{ name: “Tanvi”, role: “instructor” }]
_.groupBy(peopleList, {role: "student"})
// { false: [ { name: "Tanvi", role: "instructor" } ],
true: [ { name: "Jeremy", role: "student" },
{ name: "Pavan", role: "student" },
{ name: "Pramod", role: "student" }
]}
Javascript Libraries
Underscore also provides helper
functions.
_.isNaN()
_.isNull()
_.isEmpty()
_.isFunction()
_.isUndefined()
And more
Javascript Frameworks
Production Ready Code
3
Javascript Frameworks
Javascript is a great language, but it’s
very open, often misunderstood, and
ease to write poorly.
Using a framework can help you
conform to some common
programming practices, like MVC.
Javascript Frameworks
Backbone.js is a great framework that
provides Models, Views, and
Collections that abstract abstracts a lot
of the common functionality of a web
app.
◦ ajax calls
◦ event bindings
◦ model changes
TODO example
All Done

More Related Content

What's hot (20)

OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Java script
Java scriptJava script
Java script
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery
jQueryjQuery
jQuery
 
jQuery
jQueryjQuery
jQuery
 
jQuery
jQueryjQuery
jQuery
 
Jquery
JqueryJquery
Jquery
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
Object Oriented JavaScript - II
Object Oriented JavaScript - IIObject Oriented JavaScript - II
Object Oriented JavaScript - II
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
jQuery Introduction
jQuery IntroductionjQuery Introduction
jQuery Introduction
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
J Query
J QueryJ Query
J Query
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for Drupal
 

Similar to Advanced Javascript Concepts and Libraries for Client Side Programming

Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin developmentFaruk Hossen
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Thinqloud
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQueryKnoldus Inc.
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxMegha V
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperJon Kruger
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015jbandi
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practicesbrinsknaps
 

Similar to Advanced Javascript Concepts and Libraries for Client Side Programming (20)

Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin development
 
J query training
J query trainingJ query training
J query training
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
jQuery
jQueryjQuery
jQuery
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
J query resh
J query reshJ query resh
J query resh
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
 
Closure
ClosureClosure
Closure
 

Recently uploaded

Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 

Recently uploaded (20)

Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 

Advanced Javascript Concepts and Libraries for Client Side Programming

  • 1. Client Side Programming 2 Web Information Systems - 2015
  • 2. Advanced Javascript Let’s take this a step further 1
  • 3. Advanced Javascript Function Prototypes ● Every JavaScript object has a prototype. ● The prototype is also an object. ● All JavaScript objects inherit their properties and methods from their prototype. src: w3schools
  • 4. Advanced Javascript Object Constructor function person(first, last, age) { this.firstName = first; this.lastName = last; this.age = age; } var me = new person(“jeremy”, “Brunn”, 34) src: w3schools
  • 5. Advanced Javascript Add a property ● me.favoriteFood = “pizza” Add a property to a prototype ● person.favoriteFood = “” Add a method ● me.getName = function() { return firstName+”“+lastName; } src: w3schools
  • 6. Advanced Javascript Adding to constructors function person(first, last, age) { this.firstName = first; this.lastName = last; this.age = age; this.getName = function() { return firstName+” “+lastName; } src: w3schools
  • 7. Advanced Javascript Adding via prototype person.prototype.getName = function() { return this.firstName+” “+this.lastName; } person.prototype.setFaveFood = function(food) { this.favoriteFood = food; } src: w3schools
  • 8. Advanced Javascript Ajax and Callbacks Asynchronous Javascript and XML ● data to/from the server side $.ajax({ url: “http://www.someServer.com” }).done(success_callback) .fail(fail_callback) .always(always_callback)
  • 9. Advanced Javascript Callbacks ● functions passed to other functions as arguments. In the previous example, success_callback references a function that will be called when the ajax request completes successfully; otherwise, the function referenced by fail_callback will be called. No matter what, always_callback will be called.
  • 10. Advanced Javascript Special Considerations When requesting data from another domain, it will probably be necessary to add { dataType: “jsonp” } to the ajax argument object. ● Same-origin Policy ● Cross-origin resource sharing Also, you can’t make an ajax call to your local computer's file system, you’ll need a local server running to test.
  • 11. Advanced Javascript Javascript Aids These help clean code and suggest corrections to problems before they arise. ● JSLint ● JSHint - I prefer this one. It’s not quite so restrictive. src: w3schools
  • 13. Javascript Libraries Previously, we looked at accessing elements on the DOM with JQuery. Now we’ll examine some other things that we can do with Javascript through JQuery and other libraries.
  • 14. Javascript Libraries DOM Event listeners in JQuery $(“#submit”).click(function(e){ // do something }) is shorthand for $(document).on.(“click”, “#submit”, function(e){ // do something })
  • 15. Javascript Libraries DOM Event listeners in JQuery $(“#submit”).click(function(e){ // e is the event to handle e.preventDefault(); e.stopPropagation(); targetElement = e.currentTarget; var id = targetElement.id; // id = “submit” })
  • 16. Javascript Libraries Common Events ◦ click - an element is clicked ◦ dblclick - an element is dbl clicked ◦ focus - an element gets focus ◦ change - an element’s value changes ▫ <input>, <textarea>, or <select> ◦ hover - an element is hovered over ◦ keydown - user presses a key on keyboard ◦ keyup - user releases a key on the keyboard
  • 17. Javascript Libraries Programmatically Triggering Events $(“#submit”).trigger(“click”);
  • 18. Javascript Libraries Iterating elements in JQuery var liArray = []; $(“ul#myList > li”).each( function(i) { liArray.push( $(this).text() ); // add the li text (string) to the array // this is the current element // i is the index });
  • 19. Javascript Libraries Iterating in JQuery (and appending el) var numArray = [ 1, 2, 3, 4, 5 ]; $.each(numArray, function(index, value) { $(“#myList”).append($(“<li>”).text(value)); // adds lis to the ul “#myList” });
  • 20. Javascript Libraries Underscore An awesome library for accessing data, and much more... instead of JQuery’s “$”, use “_” First, a comparison.
  • 21. Javascript Libraries Iterating lists in underscore var numArray = [ 1, 2, 3, 4 ]; _.each(numArray, function(value, index) { $(“#myUL”).append($(“<li>”).text(value)); // adds lis to the ul “#myUL” }); Notice “value” and “index” are reversed Also, you cannot break from _.each()
  • 22. Javascript Libraries Iterating objects in undescore var numObj = { a: 1, b: 2, c: 3, d: 4 }; _.each(numObj, function(value, key) { $(“#myUL”).append( $(“<li>”).text(key+” : “+value)); // adds lis to the ul “#myUL” });
  • 23. Javascript Libraries Some more examples using this list of people objects. var peopleList = [ { name: ”Jeremy”, role: “student” }, { name: ”Tanvi”, role: “instructor” }, { name: ”Pavan”, role: “student” }, { name: “Pramod”, role: “student” } ];
  • 24. Javascript Libraries _.pluck(numObj, “name”); // [“Jeremy”, ”Tanvi”, “Pavan”, “Pramod”] _.where(numObj, { role: “instructor”}); // [{ name: “Tanvi”, role: “instructor” }] _.groupBy(peopleList, {role: "student"}) // { false: [ { name: "Tanvi", role: "instructor" } ], true: [ { name: "Jeremy", role: "student" }, { name: "Pavan", role: "student" }, { name: "Pramod", role: "student" } ]}
  • 25. Javascript Libraries Underscore also provides helper functions. _.isNaN() _.isNull() _.isEmpty() _.isFunction() _.isUndefined() And more
  • 27. Javascript Frameworks Javascript is a great language, but it’s very open, often misunderstood, and ease to write poorly. Using a framework can help you conform to some common programming practices, like MVC.
  • 28. Javascript Frameworks Backbone.js is a great framework that provides Models, Views, and Collections that abstract abstracts a lot of the common functionality of a web app. ◦ ajax calls ◦ event bindings ◦ model changes TODO example