The document discusses node.js basics including setting up a development environment, using npm commands, executing JavaScript files, using external files, function scopes, and closures. It provides code examples and explanations of key concepts like requiring modules, exports vs module.exports, and how variable scoping works differently inside and outside of functions in JavaScript.
Presentation on how Puppet has been introduced in Seat Pagine Gialle to automate system administration tasks and easy the cooperation between Ops and Others.
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
These are the slides of the code-centered presentation I did with Giorgio Cefaro at the Javascript UserGroup Roma and the PHP User Group Roma.
In this presentation we try to show many powerful features of symfony2 and its bundles to work as a backend system for single page applications.
On the client side we describe how we made a javascript editable grid using Backbone.js and its plugin for grids Backgrid.js.
Presentation on how Puppet has been introduced in Seat Pagine Gialle to automate system administration tasks and easy the cooperation between Ops and Others.
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
These are the slides of the code-centered presentation I did with Giorgio Cefaro at the Javascript UserGroup Roma and the PHP User Group Roma.
In this presentation we try to show many powerful features of symfony2 and its bundles to work as a backend system for single page applications.
On the client side we describe how we made a javascript editable grid using Backbone.js and its plugin for grids Backgrid.js.
Watch along with the video at https://www.youtube.com/watch?v=_oP1pFsOyDw
Oliver Hookins on "A Puppet Approach to Application Deployment and Automation in Nokia" at PuppetCamp Europe '11. Learn more: http://www.puppetlabs.com
Amsterdam, Netherlands, 2011.
Puppet Labs
Finding and fixing bugs is a major chunk of any developers time. This talk describes the basic rules for effective debugging in any language, but shows how the tools available in PHP can be used to find and fix even the most elusive error
Redis & ZeroMQ: How to scale your applicationrjsmelo
Presented at #PHPLX 11 July 2013
When you need to do some heavy processing how do you scale you application?
You can use Redis and ZeroMQ to leverage the heavy work for you!
With this presentation we will know more about this two technologies and how they can be used to help solve problems with the performance and scalability of your application.
Raphaël Pinson's talk on "Configuration surgery with Augeas" at PuppetCamp Geneva '12. Video at http://youtu.be/H0MJaIv4bgk
Learn more: www.puppetlabs.com
1,2편에서 다룬 chroot와 pivot_root를 통해서 root filesystem을 isolation하였습니다. 마운트 네임스페이스는 파일시스템 마운트를 isolation 하는 것으로 이미 pivot_root에서도 사용하였지만, mount 처리를 격리함으로써 컨테이너 내부의 파일시스템 구조를 독립적으로 유지합니다. 실제 도커 컨테이너의 이미지 tarball을 이용하여 pivot_root와 mount namespace까지 적용하여 실제 도커 방식과 유사하게 컨테이너를 기동하여 봅니다. 그리고, 컨테이너 이미지 용량/중복을 해결하기 위한 overlayFS 에 대하여 다룹니다.
https://netpple.github.io
Abstract: Composer is a tool for managing dependencies in PHP projects. This talk will introduce Composer and its associated package repository Packagist. The key features and benefits of using Composer will be explored and through practical demonstrations you will gain a working knowledge of using Composer for dependency management.
Watch along with the video at https://www.youtube.com/watch?v=_oP1pFsOyDw
Oliver Hookins on "A Puppet Approach to Application Deployment and Automation in Nokia" at PuppetCamp Europe '11. Learn more: http://www.puppetlabs.com
Amsterdam, Netherlands, 2011.
Puppet Labs
Finding and fixing bugs is a major chunk of any developers time. This talk describes the basic rules for effective debugging in any language, but shows how the tools available in PHP can be used to find and fix even the most elusive error
Redis & ZeroMQ: How to scale your applicationrjsmelo
Presented at #PHPLX 11 July 2013
When you need to do some heavy processing how do you scale you application?
You can use Redis and ZeroMQ to leverage the heavy work for you!
With this presentation we will know more about this two technologies and how they can be used to help solve problems with the performance and scalability of your application.
Raphaël Pinson's talk on "Configuration surgery with Augeas" at PuppetCamp Geneva '12. Video at http://youtu.be/H0MJaIv4bgk
Learn more: www.puppetlabs.com
1,2편에서 다룬 chroot와 pivot_root를 통해서 root filesystem을 isolation하였습니다. 마운트 네임스페이스는 파일시스템 마운트를 isolation 하는 것으로 이미 pivot_root에서도 사용하였지만, mount 처리를 격리함으로써 컨테이너 내부의 파일시스템 구조를 독립적으로 유지합니다. 실제 도커 컨테이너의 이미지 tarball을 이용하여 pivot_root와 mount namespace까지 적용하여 실제 도커 방식과 유사하게 컨테이너를 기동하여 봅니다. 그리고, 컨테이너 이미지 용량/중복을 해결하기 위한 overlayFS 에 대하여 다룹니다.
https://netpple.github.io
Abstract: Composer is a tool for managing dependencies in PHP projects. This talk will introduce Composer and its associated package repository Packagist. The key features and benefits of using Composer will be explored and through practical demonstrations you will gain a working knowledge of using Composer for dependency management.
My talk from DevOpsCon Berlin 2016.
Ansible is a radically simple and lightweight provisioning framework which makes your servers and applications easier to provision and deploy. By orchestrating your application deployments you gain benefits such as documentation as code, testability, continuous integration, version control, refactoring, automation and autonomy of your deployment routines, server and application configuration. Ansible uses a language that approaches plain English, uses SSH and has no agents to install on remote systems. It is the simplest way to automate and orchestrate application deployment, configuration management and continuous delivery.
In this tutorial you will be given an introduction to Ansible and learn how to provision Linux servers with a web-proxy, a database and some other packages. Furthermore we will automate zero downtime deployment of a Java application to a load balanced environment.
Dicas para publicar e manter sua aplicação NodeJS em produção. Configure o Express corretamente, trate erros, use o Nginx no seu máximo, monitore sua aplicação javascript server-side com newrelic e logs.
Capistrano deploy Magento project in an efficient waySylvain Rayé
Deploying a Magento project can be very a long and laborious task with some risks of errors. Having the good tool to prevent such a pain like Capistrano will help you to automatize such a process. Thanks such a tool you may deploy a release of your Magento project in less than 5 minutes.
A bit of history, frustration-driven development, and why and how we started looking into Puppet at Opera Software. What we're doing, successes, pain points and what we're going to do with Puppet and Config Management next.
Capistrano is an open source tool for running scripts on multiple servers. It’s primary use is for easily deploying applications. While it was built specifically for deploying Rails apps, it’s pretty simple to customize it to deploy other types of applications.
capifony is a deployment recipes collection that works with both symfony and Symfony2 applications.
Given at TechMaine's Java Users Group on Feb 26 2008
Why do we need another build tool when we already have Ant? By focusing on convention over configuration, Maven allows you to declaratively define how your project is built, which reduces a lot of the procedural code that you'd need to implement in every build file if you were using Ant. This, along with Maven's built-in management of repositories for project dependencies, allows you to streamline your build process. Ultimately Maven can reduce the amount of time that would otherwise be wasted hunting down jar files and fiddling with boilerplate build scripts.
This presentation covers Maven's core concepts. It introduces the Plugin architecture, and explain how the most popular plugins are used. It also covers the POM concept and how it relates to dependency tracking and repositories.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
7. npm common commands
Install package globally. Global packages are usually for executable
commands.
npm install <package name> -g
# example
npm install express -g
# now we can use express to generate a new app
express new app
Install package locally. Local packages are for the use of require in
the app.
cd /path/to/the/project
npm install <package name>
# example
npm install express
# now you can use `var express = require( 'express' );` in your app
8. npm common commands
Uninstall global package.
npm uninstall <package name> -g
# example
npm uninstall express -g
Uninstall local package.
cd /path/to/the/project
npm uninstall <package name>
# example
npm uninstall express
Search package.
npm search <package name>
# example
npm search express
9. npm common commands
List global packages.
npm ls -g
Update global packages.
npm update -g
List global packages detail.
npm ls -gl
Update local packages.
cd /path/to/the/project
List local packages. npm update
cd /path/to/the/project
npm ls
List local packages detail.
cd /path/to/the/project
npm ls -l
10. npm common commands
Using package.json to manage your app packages
Instead of doing
cd /path/to/the/project
npm install mongoose
npm install express
npm install jade
11. npm common commands
Using package.json to manage your app packages
Create a package.json file in the root of your app dir
{
"name": "your app name"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": ">=2.5.0"
, "jade": ">= 0.16.4"
, "mongoose": ">=2.3.10"
}
}
npm install -l
13. Use external files
node.js followsCommonJS
conventions. It uses require and
exports to communicate between
files and modules.
14. Use external files
source.txt
I am Ben.
read.js | Read the source file and print to the terminal
// require core module `file system`
var fs = require( 'fs' );
// exports 2 methods for other modules or files to use
module.exports = {
read : function( path, callback ){
// read file data synchronizely
var data = fs.readFileSync( path );
// execute the callback if there is one
callback && callback( data.toString());
},
print : function( data ){
// print out the data
console.log( data );
}
};
15. Use external files
write.js | Split the write action to this file
// require core module `file system`
var fs = require( 'fs' );
// exports 1 method for other modules or files to use
module.exports = {
write : function( filename, data ){
// write to file synchronizely
fs.writeFileSync( filename, data );
}
};
16. Use external files
run.js | Flow control
// to use methods from other files we simply use `require` with path name
var reader = require( './read' ),
writer = require( './write' );
// call `read` method from read.js to read `source.txt`
reader.read( './source.txt', function( data ){
// change `I am` to `You are`
var changed = data.replace( 'I am', 'You are' );
// print out the data
reader.print( data );
// save the changes to `changed.txt`
writer.write( './changed.txt', changed );
});
change.txt | Result
You are Ben.
17. Use external files
What’s the differences between the following 3?
var something = require( './something' );
var something = require( './something.js' );
var something = require( 'something' );
18. Use external files
exports VS module.exports
Using module.exports
module.exports = {
do_a : function(){
// do something ...
},
do_b : function(){
// do something ...
}
};
19. Use external files
exports VS module.exports
Using exports
exports.do_a = function(){
// do something ...
};
exports.do_b = function(){
// do something ...
};
20. Use external files
exports VS module.exports
We can use both in another file with
var something = require( './something' );
something.do_a();
something.so_b();
21. Use external files
exports VS module.exports
What if we want to use the entire module as a function like the following?
var something = require( './something' );
something();
22. Use external files
exports VS module.exports
// this works
module.exports = function(){
// do something
};
// this is not going to work
exports = function(){
// do something
};
23. Use external files
require only loads the file once and
will store them in the memory, so don’t be
afraid to use it.
24. Function scope
Javascript uses function as scope.
Declare a function inside another
function creates a different scope.
25. Function scope
function outer_scope(){
var a = 'I am `a` from outer scope',
b = 'I am `b` from outer scope';
console.log( 'logging from outer scope before inner scope function declaration' );
console.log( 'a: ' + a );
console.log( 'b: ' + b );
console.log( '------------------------------------------' );
function inner_scope_1(){
console.log( 'logging from inside function inner_scope_1 before variable declaration' );
console.log( 'a: ' + a );
a = 'I will overwrite the outer scope `a`';
console.log( 'logging from inside function inner_scope_1 after variable declaration' );
console.log( 'a: ' + a );
console.log( '------------------------------------------' );
}
function inner_scope_2(){
console.log( 'logging from inside function inner_scope_2 before variable declaration' );
console.log( 'b: ' + b );
var b = 'I will not overwrite the outer scope `b`';
console.log( 'logging from inside function inner_scope_2 after variable declaration' );
console.log( 'b: ' + b );
console.log( '------------------------------------------' );
}
26. Function scope
function inner_scope_2(){
console.log( 'logging from inside function inner_scope_2 before variable declaration' );
console.log( 'b: ' + b );
var b = 'I will not overwrite the outer scope `b`';
console.log( 'logging from inside function inner_scope_2 after variable declaration' );
console.log( 'b: ' + b );
console.log( '------------------------------------------' );
}
inner_scope_1();
inner_scope_2();
a = 'I will be the new `a`';
b = 'I will be the new `b`';
console.log( 'logging from outer scope after inner scope executed' );
console.log( 'b: ' + b );
console.log( 'b: ' + b );
console.log( '------------------------------------------' );
}
outer_scope();
27. Function scope
logging from outer scope before inner scope function declaration
a: I am `a` from outer scope
b: I am `b` from outer scope
------------------------------------------
logging from inside function inner_scope_1 before variable declaration
a: I am `a` from outer scope
logging from inside function inner_scope_1 after variable declaration
a: I will overwrite the outer scope `a`
------------------------------------------
logging from inside function inner_scope_2 before variable declaration
b: undefined
logging from inside function inner_scope_2 after variable declaration
b: I will not overwrite the outer scope `b`
------------------------------------------
logging from outer scope after inner scope executed
b: I will be the new `b`
b: I will be the new `b`
------------------------------------------
28. Closure
A closure is a function together
with a referencing environment for the
non-local variables of that function.
29. Closure
function photo(){
var name = 'ben';
return{
say_my_name : function(){
console.log( name );
},
rename : function( new_name ){
name = new_name;
}
};
}
var pic = new photo;
pic.say_my_name();
pic.rename( 'bibi' );
pic.say_my_name();
30. Javascript `this`
this points to the current scope object.
var something, another;
something = {
x : 'x',
print : function( callback ){
callback && callback.call( this );
console.log( this.x );
}
};
another = {
x : 'a',
set_x : function(){
this.x = 'b';
}
};
31. Javascript `this`
this points to the current scope object.
// situation a
something.print( function(){
another.set_x();
});
// situation b
something.print( another.set_x );
// situation c
something.print( function(){
another.set_x.call( this );
});
32. Javascript `this`
Common mistake
var example = {
name : 'who',
wrong : function(){
setTimeout( function(){
console.log( this.name );
}, 0 );
},
right : function(){
var self = this;
setTimeout( function(){
console.log( self.name );
}, 0 );
}
};
example.wrong();
example.right();
33. call and apply
call and apply invoke the function and switch the
function context with the first argument
function fn( arg1, arg2,... ){
// do something
}
fn( arg1, arg2,... );
fn.call( context, arg1, arg2,... );
fn.apply( context, [ arg1, arg2,... ]);
34. call and apply
A real world use case
function Album( id, title, owner_id ){
this.id = id;
this.name = title;
this.owner_id = owner_id;
};
Album.prototype.get_owner = function( callback ){
var self = this;
$.get( '/owners/' + this.owner_id , function( data ){
callback && callback.call( self, data.name );
});
};
var album = new Album( 1, 'node.js conf', 2 );
album.get_owner( function( owner ){
alert( 'The album' + this.name + ' belongs to ' + owner );
});
35. call and apply
Speed
Function invoke with call is slightly faster than with apply. But
don’t worry, you really can’t tell the difference, use whatever suits
you.
36. Callbacks
A callback is a function to be
executed after another function is
executed.
37. Callbacks
Normal case
function do_a(){
console.log( '`do_a`: this comes out first');
}
function do_b(){
console.log( '`do_b`: this comes out later' );
}
do_a();
do_b();
Result
`do_a`: this comes out first
`do_b`: this comes out later
38. Callbacks
This might happen
function do_a(){
setTimeout( function(){
console.log( '`do_a`: this takes longer than `do_b` ');
}, 3000 );
}
function do_b(){
console.log( '`do_b`: this is supposed to come out after `do_a`
but it comes out before `do_a`' );
}
do_a();
do_b();
Result
`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`
`do_a`: this takes longer than `do_b`
39. Callbacks
The right way
function do_a( callback ){
// simulate a time consuming function
setTimeout( function(){
console.log( '`do_a`: this takes longer than `do_b`' );
// if callback exist execute it
callback && callback();
}, 3000 );
}
function do_b(){
console.log( '`do_b`: now we can make sure `do_b` comes out after `do_a`' );
}
do_a( function(){
do_b();
});
Result
`do_a`: this takes longer than `do_b`
`do_b`: now we can make sure `do_b` comes out after `do_a`
40. Callbacks
Different ways of applying a callback
function basic( callback ){
console.log( 'do something here' );
var result = 'i am the result of `do something` to be past to the callback';
// if callback exist execute it
callback && callback( result );
}
basic( function( result ){
console.log( 'this callback is going to print out the result from the function `basic`' );
console.log( result );
});
Result
do something here
this callback is going to print out the result from the function `basic`
i am the result of `do something` to be past to the callback
41. Callbacks
Different ways of applying a callback
function callbacks_with_call( arg1, arg2, callback ){
console.log( 'do something here' );
var result1 = arg1.replace( 'argument', 'result' ),
result2 = arg2.replace( 'argument', 'result' );
this.data = 'i am some data that can be use for the callback funciton with `this`
key word';
// if callback exist execute it
callback && callback.call( this, result1, result2 );
}
( function(){
var arg1 = 'i am argument1',
arg2 = 'i am argument2';
callbacks_with_call( arg1, arg2, function( result1, result2 ){
console.log( 'this callback is going to print out the results from the function
`callbacks_with_call`' );
console.log( 'result1: ' + result1 );
console.log( 'result2: ' + result2 );
console.log( 'data from `callbacks_with_call`: ' + this.data );
});
})();
42. Callbacks
Different ways of applying a callback
Result
do something here
this callback is going to print out the results from the function `callbacks_with_call`
result1: i am result1
result2: i am result2
data from `callbacks_with_call`: i am some data that can be use for the callback
function with `this` key word
43. Callbacks
Different ways of applying a callback
// this is similar to `callbacks_with_call`
// the only difference is we use `apply` instead of `call`
// so we need to pass arguments as an array
function callbacks_with_apply( arg1, arg2, callback ){
console.log( 'do something here' );
var result1 = arg1.replace( 'argument', 'result' ),
result2 = arg2.replace( 'argument', 'result' );
this.data = 'i am some data that can be use for the callback function with
`this` key word';
// if callback exist execute it
callback && callback.apply( this, [ result1, result2 ]);
}
44. Callbacks
Different ways of applying a callback
( function(){
var arg1 = 'i am argument1',
arg2 = 'i am argument2';
callbacks_with_apply( arg1, arg2, function( result1, result2 ){
console.log( 'this callback is going to print out the result from the function `callbacks_with_apply`' );
console.log( 'result1: ' + result1 );
console.log( 'result2: ' + result2 );
console.log( 'data from `callbacks_with_apply`: ' + this.data );
});
})();
Result
do something here
this callback is going to print out the result from the function `callbacks_with_apply`
result1: i am result1
result2: i am result2
data from `callbacks_with_apply`: i am some data that can be use for the callback
function with `this` key word
45. Events
Because javascript is an event driven
language, we often have to deal with nested
callbacks. It looks ugly and your code is
tighten up.
do_a( function(){
do_b( function(){
do_c( function(){
do_d( function(){
...
});
});
});
});
46. Events
With EventEmitter of node.js
events module we can flatten the nested
callbacks
event.js
var event = require( 'events' ).EventEmitter;
module.exports = new event;
47. Events
do_a.js
var event = require( './event' );
module.exports = function(){
console.log( 'we are going to call do_a' );
event.emit( 'do_a' );
};
do_b.js
var event = require( './event' );
module.exports = function(){
event.on( 'do_a', function(){
console.log( 'we are going to call do_b' );
event.emit( 'do_b' );
});
};
48. Events
do_c.js
var event = require( './event' );
module.exports = function(){
event.on( 'do_b', function(){
console.log( 'we are going to call do_c' );
event.emit( 'do_c' );
});
};
do_d.js
var event = require( './event' );
module.exports = function(){
event.on( 'do_c', function(){
console.log( 'we are going to call do_d' );
event.emit( 'do_d' );
});
};
49. Events
run.js
var event, todos;
event = require( './event' );
todos = [ './do_d', './do_c', './do_b', './do_a' ];
event.on( 'do_a', function(){
console.log( 'i can do something to do_a out side of do_a' );
});
event.on( 'do_b', function(){
console.log( 'i can do something to do_b out side of do_b' );
});
event.on( 'do_c', function(){
console.log( 'i can do something to do_c out side of do_c' );
});
event.on( 'do_d', function(){
console.log( 'i can do something to do_d out side of do_d' );
});
todos.forEach( function( name ){
require( name )();
});