Download presentation
Presentation is loading. Please wait.
1
Web-Technology Lecture 7
2
Callback functions
3
a bit more about functions in JS
functions are first-class objects Can be stored in variables, Passed as arguments to, created in, and returned by other functions function myFunction() { alert (typeof(myFunction)); function itsFunction(x) {alert (typeof(x.prototype));} return(itsFunction(myFunction)); }
4
..and a bit more (with an error report)
<button id=“mb” onclick=”check();">Try it</button> <!– will work --> <button id=“mb” onclick=”check">Try it</button> <!– will NOT work --> <script> document.getElementById(“mb”).onclick = check; // will work document.getElementById(“mb”).onclick = check(); // will NOT work as you want </script> var currentTime = function() { var d = new Date(); return d.getTime(); } var a = currentTime(); //The current time at the point a is defined... var b = currentTime; //b is a functional reference to currentTime... var c = b(); //The current time when variable c is defined var d = c; //The current time when variable c was defined
5
Callback functions callback function is a function that is passed to another function as a parameter and called-back within the body of that function when a callback function is passed, only its definition is passed = the callback function is not executed yet It’s executed later, when “called back” inside the containing function body function outer (outerParams, callback) { … callback(callbackParams); } function inner (innerParms) { … }; outer (params, inner); // callback is not executed here // ..but here
6
Anonymous callback functions
Sometimes, you do not want/need to define a named callback function function outer (outerParams, callback) { … callback(callbackParams); } outer (params, function (innerParms) { … }; );
7
Anonymous callback functions
Sometimes, you do not want/need to define a named callback function function outer (outerParams, callback) { … callback(callbackParams); } outer (params, function (innerParms) { … }; );
8
Callback functions – FP perspective
An elegant way of code structuring and reuse function doMath(arg1, arg2, oper){ alert(oper(arg1,arg2)); } function add (x,y){ return (x+y); function multiply (a,b) { return(a*b); doMath(5,10,add); doMath(5,10, multiply);
9
Callback functions – workflow control perspective
function writeToFile(file) { fileObject = open(file); // now that we have WAITED for the file to open, we can write to it fileObject.write("We are writing to the file."); // now we can continue doing the other, totally unrelated things} // we pass writeToFile (as A CALLBACK FUNCTION!) to the open function fileObject = open(file, writeToFile); function writeToFile(file) { fileObject.write("We are writing to the file."); } // execution continues flowing -- we don't wait for the file to be opened // ONCE the file is opened we write to it, but while we wait WE CAN DO OTHER THINGS!
10
Callback functions – why do we need them?
JavaScript is single-threaded and synchronous There are to many workflow-blocking events that can happen: A user interacting with the interface A webserver executing a code A DB server running a query A slow network connection A large file (many files) loading Callbacks enable asynchronous, no-blocking implementation for handling such events. A processing function is called-back once: a user provides input A webserver sends a new request A DB server provides a result set Data over network has been received Integral part of Ajax and jQuery
11
Callback Hell Sometimes it can get our of control refuel();
startEngine(); takeOff(); land(); // ... done refuel(function() { startEngine() takeOff() land() // ... done }) refuel(function() { startEngine(function(){ takeOff() land() // ... done }) refuel(function() { startEngine(function() { takeOff(function() { land() // ... done }) refuel(function() { startEngine(function() { takeOff(function() { land(function() { // ... done })
12
Callback hell Problems: Solutions:
Loss of control flow Loss of error handling Loss of code understanding Solutions: Name your functions instead of declaring them anonymously Separate code into blocks More solutions for you to explore (beyond this course): Generators* async functions Promises
13
jQuery
14
jQuery: what and why A fast, concise, JavaScript library that simplifies for web developers: DOM traversal, event handling, animation, Ajax, etc. jQuery has changed the way that millions of people write JavaScript first released in 2006; now: 72% of all websites use it (next – Bootstrap – 15%) free and open source cross-browser support lightweight intuitive and easy to learn - uses familiar CSS syntax and Safe, efficient and extensible
15
Selectors jQuery extensively uses CSS selectors:
.class #id element [attribute] [attribute=value] :first-child :last-child :root … .. And introduces new ones: div:first, h3:last li:eq(2) :header :hidden, :visible :input, :text, :password, :radio, :submit... div:contains(“Hello”) ... Lennart Herlaar - UU
16
jQuery: hello world! Lennart Herlaar - UU
17
jQuery(document).ready function
Everything happens within the jQuery function $ is the alias for jQuery $(document).ready(function(){ // rest of jQuery code }); document.addEventListener("DOMContentLoaded", myFunc, false); window.addEventListener("load", myFunc, false); jQuery(document).ready(handler); jQuery().ready(handler); jQuery(handler); $(document).ready(handler); $().ready(handler); $(handler); = Lennart Herlaar - UU
18
jQuery collections $('div.section') returns a jQuery collection
You can treat it like an array $('div.section').length = no. of matched elements $('div.section')[0] - the first div DOM element You can call methods on it: $('div.section').size() = no. of matched elements $('div.section').each(function() { console.log(this); }); Lennart Herlaar - UU
19
jQuery: Modifying your document
Change HTML content: $('span#msg').text('The thing was updated!'); $('div#intro').html('<em>Look, HTML</em>'); Change attributes: $('a.nav').attr('href', ' $('#intro').removeAttr('id'); Changing CSS: $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highlighted'); $('p').css('font-size', '20px'); $('p').css({'font-size': '20px', color: 'red'});
20
Traversing DOM jQuery provides enhanced methods for traversing the DOM
$('div.section').parent() $('div.section').next() $('div.section').prev() $('div.section').nextAll('div') $('h1:first').parents()
21
Handling events $('a:first').click(function(ev) {
$(this).css({backgroundColor: 'orange'}); return false; // Or ev.preventDefault(); }); Or $(‘a:first’).on("click", function(ev) { ev.preventDefault();
22
jQuery - chaining Most jQuery methods return another jQuery object - usually one representing the same collection. This means you can chain methods together: $('div.section').hide().addClass('gone'); Some methods return a different collection. You can call .end() to revert to the previous collection $('#intro').css('color', '#cccccc').find(’div').addClass ('highlighted').end().find(’span').css('color', 'red');
23
Client-Server Architecture
24
Models of computing Standalone computing Mainframe computing
Terminal access, teleprocessing, time sharing File server Central storage, distributed processing Client/server model Servers and clients that manage and use the resources Distributed processing P2P computing Every host is a client and a server at the same time Lennart Herlaar - UU
25
2-tier client-server model
Traditional client/server model Two tiers “Fat Client” contains user interface and application logic Server includes database and transaction logic Problems: potential race conditions: two desktop applications attempts to update the server at the same time the client application has to be installed (and updated/mantained) on each client Lennart Herlaar - UU
26
Multitier client server model
Three-tier client/server model Client contains user interface (“thin” client) Application server contains application logic / business rules (middleware) Database server manages the database and transactional logic N-tier client/server model Further splitting if necessary e.g., presentation, application, business logic and data tiers Three-tier C/S model is good fit for Web-based Client-Server applications Web-browser is a thin client responsible for presentation Web-server serves the application logic Database server manages the data tier Lennart Herlaar - UU
27
Previous generations of Web applications
First Generation Web Applications page oriented every action is embedded in its own web page script each script acts as a separate transaction executing app. logic and generating the GUI Second Generation Web application GUI logic (page generating scripts) is separated from the application logic (objects and components) on the server Dedicated frameworks (ASP.NET, Spring MVC (Java), erc.) Lennart Herlaar - UU
28
RIA: Rich Internet Applications
User interface looks more like a desktop application GUI logic moves to the browser/dedicated app Independence of client and server implementations Separate testing of the interface and the services Proliferation of reusable GUI components Various client platforms supported by the same services Client-server exchange is data (XML or JSON) not GUI code (HTML, CSS and JavaScript)
29
Server side scripting and programming languages
We have been learning JavaScript. Now we need to learn another language? Wide variety: ColdFusion Java .NET framework ASP.NET C# Perl PHP Python Ruby SSJS …
30
The Server-side JavaScripting
31
Background V8 is an open source JavaScript engine developed by Google. Its written in C++ and is used in Google Chrome Browser. Node.js runs on V8. It was created by Ryan Dahl in 2009. Latest version is 7.7.1 Ii is Open Source. It runs on Linux, Windows, Mac Os systems, can also run on Windows systems. It is very popular with Industry, including PayPal, Microsoft, IBM, Groupon, etc.
32
Introduction: Basic In simple words Node.js is ‘server-side JavaScript’. In not-so-simple words Node.js is a high-performance network applications framework, well optimized for high concurrent environments. It’s a command line tool. In ‘Node.js’ , ‘.js’ doesn’t mean that its solely written in JavaScript. It is ~40% JS and ~60% C++. From the official site: ‘Node's goal is to provide an easy way to build scalable network programs’
33
Introduction: Advanced (& Confusing)
Node.js uses an event-driven, non-blocking I/O model, which makes it lightweight. It makes use of event-loops via JavaScript’s callback functionality to implement the non-blocking I/O. Programs for Node.js are written in JavaScript but not in the same JavaScript we are use to. There is no DOM implementation provided by Node.js, i.e. you can not do this: var element = document.getElementById(“elementId”); Everything inside Node.js runs in a single-thread.
34
Example-1: Getting Started & Hello World
Install/build Node.js. Open your favorite editor and start typing JavaScript. When you are done, open cmd/terminal and type this: ‘node YOUR_FILE.js’ Here is a simple example, which prints ‘hello world’ var sys = require(“sys”); setTimeout(function(){ sys.puts(“world”);},3000); sys.puts(“hello”); //it prints ‘hello’ first and waits for 3 seconds and then prints ‘world’
35
Some Theory: Event-loops
Event-loops are the core of event-driven programming, almost all the UI programs use event-loops to track the user event, for example: Clicks, Ajax Requests etc. Client Clients send HTTP requests to Node.js server Event loop returns result to client An Event-loop is woken up by OS, passes request and response objects to the thread-pool Event loop (main thread) Response is sent back to main thread via callback Long-running jobs run on worker threads C++ Threadpool (worker threads)
36
Some Theory: Non-Blocking I/O
Traditional I/O var result = db.query(“select x from table_Y”); doSomethingWith(result); //wait for result! doSomethingWithOutResult(); //execution is blocked! Non-traditional, Non-blocking I/O db.query(“select x from table_Y”,function (result){ }); doSomethingWithOutResult(); //executes without any delay!
37
What can you do with Node.js ?
You can create an HTTP server and print ‘hello world’ on the browser in just 4 lines of JavaScript. (Example included) You can create a TCP server similar to HTTP server, in just 4 lines of JavaScript. (Example included) You can create a DNS server. You can create a Static File Server. You can create a Web Chat Application like GTalk in the browser. Node.js can also be used for creating online games, collaboration tools or anything which sends updates to the user in real-time.
38
Example -2 &3 (HTTP Server & TCP Server)
Following code creates an HTTP Server and prints ‘Hello World’ on the browser: Here is an example of a simple TCP server which listens on port 6000 and echoes whatever you send it: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(5000, " "); var net = require('net'); net.createServer(function (socket) { socket.write("Echo server\r\n"); socket.pipe(socket); }).listen(6000, " ");
39
Node.js Ecosystem Node.js heavily relies on modules, in previous examples require keyword loaded the http & net modules. Creating a module is easy, just put your JavaScript code in a separate js file and include it in your code by using keyword require, like: var modulex = require(‘./modulex’); Libraries in Node.js are called packages and they can be installed by typing npm install “package_name”; //package should be available in npm nmpjs.org NPM (Node Package Manager) comes bundled with Node.js installation.
40
When to use Node.js? Node.js is good for creating streaming based real-time services, web chat applications, static file servers etc. If you need high level concurrency and not worried about CPU- cycles. If you are great at writing JavaScript code because then you can use the same language at both the places: server-side and client- side. More can be found at: when-to-use-nodejs
41
Example-4: Twitter Streaming
Install nTwitter module using npm: Npm install ntwitter Code: var twitter = require('ntwitter'); var twit = new twitter({ consumer_key: ‘c_key’, consumer_secret: ‘c_secret’, access_token_key: ‘token_key’, access_token_secret: ‘token_secret’}); twit.stream('statuses/sample', function(stream) { stream.on('data', function (data) { console.log(data); }); });
42
Some Node.js benchmarks
Taken from: A benchmark between Apache+PHP and node.js, shows the response time for 1000 concurrent connections making 10,000 requests each, for 5 tests. Taken from: The benchmark shows the response time in milli-secs for 4 evented servers.
43
When to not use Node.js When you are doing heavy and CPU intensive calculations on server side, because event-loops are CPU hungry. Node.js API is still in beta, it keeps on changing a lot from one revision to another and there is a very little backward compatibility. Most of the packages are also unstable. Therefore is not yet production ready. Node.js is a no match for enterprise level application frameworks like Spring(java), Django(python), Symfony(php) etc. Applications written on such platforms are meant to be highly user interactive and involve complex business logic. Read further on disadvantages of Node.js on Quora: disadvantages-of-using-Node-js
44
Appendix-1: Who is using Node.js in production?
Yahoo! : iPad App Livestand uses Yahoo! Manhattan framework which is based on Node.js. LinkedIn : LinkedIn uses a combination of Node.js and MongoDB for its mobile platform. iOS and Android apps are based on it. eBay : Uses Node.js along with ql.io to help application developers in improving eBay’s end user experience. Dow Jones : The WSJ Social front-end is written completely in Node.js, using Express.js, and many other modules. Complete list can be found at: and-Companies-Using-Node
45
Appendix-2: Resource to get started
Watch this video at Youtube: Read the free O’reilly Book ‘Up and Running with Visit for Info/News about Node.js Watch Node.js For anything else Google!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.