selfisnotaJavaScriptkeyword!Programmersusethatwhendefiningclassestohavealwaysvalidreferencetoobjectitself.varPerson=function(){varself=this;// private functionfunctionsay(what){alert(what);}self.fetchSomething=function(){varxhr=Ti.Network.createHTTPClient({onload: function(){// in this case 'this' is referencing to xhr!!!say(this.responseText);}});xhr.open('GET','http://www.whatever.com');xhr.send();}returnself;}varp=newPerson();p.fetchSomething();
attach callback function, to be invoked later, when $post returns
futurefunc<oc>De is called with the return value of <code>$.post as its argument
HTTP Server Examples
var http = require('http');
var server = http.createServer();
server.on('request', function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000);
consol.log('Server running at http://localhost:3000');
As a result, a process, which consists of props, reactors, events, functions are generated. You can query props, reactors, events, functions from the process.
Streaming Example
var fs = require('fs');
var stream = fs.createReadStream('./resource.json')
stream.on('data', function(chunk) {
console.log(chunk);
})
stream.on('end', function () {
console.log('finished');
})
Streaming Pipe (Session) Example
var http = require('http');
var fs = require('fs');
http.createServer( function (req, res) {
res.writeHead(200, {'Content-Type': 'image/png' });
fs.createReadStream('./image.png').pipe(res);
}).listen(3000);
console.log('Server running at http://localhost:3000');
upon request ("req"), a handler creates a stream over a predefined file, and create a pipe that sends the data to client (res)
Asynchronous Programming Techniques in Node
Handling One-Off Events with Callbacks
A callback is a code which will be executed for a future response to a request.
e.g. You request DB query, which is time-consuming, in a nonblocking way and register a callback to be called when DB query is finished with a result.
A event listener is a callback which is associated with a conceptual event.
e.g. a mouse click is a event.
e.g. in Node, an HTTP server emits a request event when an HTTP request is made
Handling Repetitive Events with Event Emitters
An event emitter can fire events and includes the ability to handle those events when triggered.
e.g. Node API components, such as HTTP server, TCP server, and streams, are implemented as event emitters
Challenges in Asynchronous Development
Common Usages
Socket.IO for MQ
virtual channel: i.e. publish/subscribe message model
event emitter: some virtual proxy which represents a remote object