As a guest speaker in NCU, I gave a talk about some best practices of JavaScript programming to college students. It covers basic JavaScript elements and some common pitfalls while dealing with asynchronous programming.
As a guest speaker in NCU, I gave this second talk about some more advanced practices of JavaScript programming. It summarised our experience learned from developing Mozilla/Gaia project, including the way to deal with asynchronous code flow with the event-driven model.
In recent years we have seen explosion of languages which run on Java Virtual Machine. We also have seen existing languages getting their implementations being rewritten to JVM. With all of the above we have seen rapid development of tools like parsers, bytecode generators and such, even inside JVM we saw initiatives like Da Vinci Machine Project, which led to invoke dynamic in JDK 7 and recent development of Graal and Truffle projects.
Is it really hard to write new programming language running on JVM? Even if you are not going to write your own I think it is worth to understand how your favorite language runs undercover, how early decisions can impact language extensibility and performance, what JVM itself and JVM ecosystem has to offer to language implementors.
During session I will try to get you familiar with options you have when choosing parsers and byte code manipulation libraries. which language implementation to consider, how to test and tune your "new baby". Will you be able after this session to develop new and shiny language, packed with killer features language? No. But for sure you will understand difference between lexers and parsers, how bytecode works, why invoke dynamic and Graal and Truffle are so important to the future of JVM platform. Will we have time to write simple, compiled language?
Yes, we will, just to show you that even person who didn't studied computer science, compilers theory, and for majority of his life didn't know what AST is, can do it :)
In this session, Aaron Gustafson introduces attendees to the client-side scripting language known as JavaScript. After being taken on a quick tour through the language's features and syntax, attendees will be introduced through a series of examples to ways in which JavaScript can progressively enhance the user experience and really make their designs sing. This session also introduces attendees to several JavaScript libraries and demonstrate how to execute the same task in each.
This presentation will give you a brief background to JavaScript, what it is and where it comes from. Then it will walk you through general pitfalls, best practices and more advanced topics such as object-orientation, scope and closures.
As a guest speaker in NCU, I gave this second talk about some more advanced practices of JavaScript programming. It summarised our experience learned from developing Mozilla/Gaia project, including the way to deal with asynchronous code flow with the event-driven model.
In recent years we have seen explosion of languages which run on Java Virtual Machine. We also have seen existing languages getting their implementations being rewritten to JVM. With all of the above we have seen rapid development of tools like parsers, bytecode generators and such, even inside JVM we saw initiatives like Da Vinci Machine Project, which led to invoke dynamic in JDK 7 and recent development of Graal and Truffle projects.
Is it really hard to write new programming language running on JVM? Even if you are not going to write your own I think it is worth to understand how your favorite language runs undercover, how early decisions can impact language extensibility and performance, what JVM itself and JVM ecosystem has to offer to language implementors.
During session I will try to get you familiar with options you have when choosing parsers and byte code manipulation libraries. which language implementation to consider, how to test and tune your "new baby". Will you be able after this session to develop new and shiny language, packed with killer features language? No. But for sure you will understand difference between lexers and parsers, how bytecode works, why invoke dynamic and Graal and Truffle are so important to the future of JVM platform. Will we have time to write simple, compiled language?
Yes, we will, just to show you that even person who didn't studied computer science, compilers theory, and for majority of his life didn't know what AST is, can do it :)
In this session, Aaron Gustafson introduces attendees to the client-side scripting language known as JavaScript. After being taken on a quick tour through the language's features and syntax, attendees will be introduced through a series of examples to ways in which JavaScript can progressively enhance the user experience and really make their designs sing. This session also introduces attendees to several JavaScript libraries and demonstrate how to execute the same task in each.
This presentation will give you a brief background to JavaScript, what it is and where it comes from. Then it will walk you through general pitfalls, best practices and more advanced topics such as object-orientation, scope and closures.
Writing JavaScript as a hobby and writing JavaScript as a job are two very different things. Learn some common practices for making your JavaScript friendly to a team environment.
One of JavaScript’s strengths is how it handles asynchronous code. Async is one of the most important and often misunderstood part of Javascript or any other language. Async is hard because we, as human beings, can’t do two conscious actions at once and think about both of them at the same moment. In this talk we will see how asynchronous JavaScript evolved over the years. It all started with callbacks… and it landed on generators!
Performance Optimization and JavaScript Best PracticesDoris Chen
Performance optimization and JavaScript best practices tips are discussed in the talk. Here are some of the tips:
Put stylesheets at the top (css)
Move scripts to the bottom (javascript)
Provide a clean separation of content, CSS, and JavaScript
De-reference unused objects
Think Asynchronous
Working with Objects
Defer Loading Resources
Use JSLint -- Code Quality Tool
Reduce the size of JavaScript file
gzip
General JavaScript Coding Best Practices
Use === Instead of ==
Eval = Bad
Don’t Use Short-Hand
Reduce Globals: Namespace
Don't Pass a String to "SetInterval" or "SetTimeOut"
Use {} Instead of New Object()
Use [] Instead of New Array()
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
Hash Tag Killer - Gamification in customer engagement - Manu Melwin Jotmanumelwin
NBC Universal's USA Network enlisted the help of gamification startup San Jose, Calif.-based Bunchball in July 2010 to increase engagement on the website for Psych, one of its TV shows.
Writing JavaScript as a hobby and writing JavaScript as a job are two very different things. Learn some common practices for making your JavaScript friendly to a team environment.
One of JavaScript’s strengths is how it handles asynchronous code. Async is one of the most important and often misunderstood part of Javascript or any other language. Async is hard because we, as human beings, can’t do two conscious actions at once and think about both of them at the same moment. In this talk we will see how asynchronous JavaScript evolved over the years. It all started with callbacks… and it landed on generators!
Performance Optimization and JavaScript Best PracticesDoris Chen
Performance optimization and JavaScript best practices tips are discussed in the talk. Here are some of the tips:
Put stylesheets at the top (css)
Move scripts to the bottom (javascript)
Provide a clean separation of content, CSS, and JavaScript
De-reference unused objects
Think Asynchronous
Working with Objects
Defer Loading Resources
Use JSLint -- Code Quality Tool
Reduce the size of JavaScript file
gzip
General JavaScript Coding Best Practices
Use === Instead of ==
Eval = Bad
Don’t Use Short-Hand
Reduce Globals: Namespace
Don't Pass a String to "SetInterval" or "SetTimeOut"
Use {} Instead of New Object()
Use [] Instead of New Array()
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
Hash Tag Killer - Gamification in customer engagement - Manu Melwin Jotmanumelwin
NBC Universal's USA Network enlisted the help of gamification startup San Jose, Calif.-based Bunchball in July 2010 to increase engagement on the website for Psych, one of its TV shows.
World Peace Game - Gamification in education - Manu Melwin Joymanumelwin
An ingenious creation of Virginia educator John Hunter, the World Peace Game is a rich and elaborate political simulation that invites young students to explore a world not unlike our own, consisting of four or five prominent nations.
Turning The Tides With Global Customer Advocacy
with James, Scott President at Brightpearl Inc.
Visit www.advocamp.com for everything you need to know about Advocamp - the biggest customer experience, engagement and advocacy event of the year.
Change of Pace, Change of Culture- TPPC 2017Rachael Arroyo
Everyone knows there is a difference between outdoor Seasonal staff and indoor year-round staff. The pace is different, the culture is different, even the needs are different for the facility and the staff. This session will equip you with ideas of how to identify, address, and plan in order to mitigate issues between seasons as well as staff buy in to ensure it is a smooth transition.
Introduction to Design Patterns and SingletonJonathan Simon
This is Class 1 on a 6 week course I taught on Software Design Patterns.
This course provides an introduction into Design Patterns and delves into the Singleton Pattern.
Class based on "Head First Design Patterns."
Cover the advantages of test driven development, the reasons for pushing it all the way to the browser level, and then explore the options for testing JavaScript, look at some examples, and then integrate the tests into our existing development workflow.
Miller Columns (used in iPhone and Mac Finder) are an elegant way of displaying and navigating a tree. This talk describes a JavaScript implementation of Miller Columns, and why JavaScript needs modules and a standard library.
Not so long ago one of our colleagues left the team and joined one company developing software for embedded systems. There is nothing extraordinary about it: in every firm people come and go, all the time. Their choice is determined by bonuses offered, the convenience aspect, and personal preferences. What we find interesting is quite another thing. Our ex-colleague is sincerely worried about the quality of the code he deals with in his new job. And that has resulted in us writing a joint article. You see, once you have figured out what static analysis is all about, you just don't feel like settling for "simply programming".
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2015.
http://www.ivanomalavolta.com
Konstantin Knizhnik: static analysis, a view from asidePVS-Studio
The article is an interview with Konstantin Knizhnik taken by Andrey Karpov, "Program Verification Systems" company's worker. In this interview the issues of static code analysis, relevance of solutions made in this sphere and prospects of using static analysis while developing applications are discussed.
Slides of the talk I gave at the .NET-day 2015 @L'Aquila (Italy).
Roadmap:
Use the DOM efficiently
Master events
Be smart with the network
Take care of memory issues
Take advantage of CSS3 features
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2014.
http://www.ivanomalavolta.com
Rust + python: lessons learnt from building a toy filesystemChengHui Weng
In this slides I listed what I have learnt when I was working on my toy FUSE based file system in Rust for Python. By using PyO3, to bind Rust with Python becomes really easy, but the unavoidable type conversions affect the whole Rust code design and efficiency.
This is as a lighting talk for WebHack#16 meet up: https://webhack.connpass.com/event/99735/
In this WebHack talk I shared about what I have learnt from SpiderMonkey: the JavaScript engine inside Firefox browser. I extracted and concluded 3 slides made in the past, and updated some few content.
In this WebHack talk I shared my experience about microservices, Docker, Kubernetes and Kong, an API gateway by Mashape. Since they are based on a real working system, this slides is majorly for how to build the whole thing up, not about detailed internal implementation. Although I included some details and reference in order to make it more comprehensive.
In the recent Functional Thursday meetup, I gave this talk about SpiderMonkey: Mozilla's JavaScript engine used in Firefox. The content covers the architecture and some interesting internal implementations.
In this talk I introduced Yampa, the AFRP framework in Haskell, and the Quake-like game made by it. The content convers the basic of Functional Reactive Programming, Haskell Arrow, Yampa itself, time-space leak, etc.
Introduction to Basic Haskell Components (In Chinese)ChengHui Weng
In 2012, we had the first Chinese functional meetup about general functional programming techniques in Taipei. I gave this talk to introduce several classes in the famous Typeclassesopedia article.
A talk in JSDC.tw 2014. I introduce the advantage and disadvantage to write JavaScript in functional style. It covers simple Functional Programming concepts, how JavaScript becomes more functional, and all the difficulties people may encounter.
This is the slide for what I shared in JS Group meetup, 2014, Taiwan. It covers what JavaScript could do for making the program more "functional", the benefits, price and the limitation.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
3. I'm
Working for Mozilla as a Software Engineer; 2yr+
Responsible for FirefoxOS screen locker (LockScreen)
ECMAScript experience: 6yr+
Free Software and Open Source are important to me
And I'm also a language enthusiast
Like to research programming language themselves
Haskell, Ruby, JavaScript
Java, PHP, Erlang, Python, C/C++
4. Find me at
Mail: gweng@mozilla.com
IRC: snowmantw
Twitter: @GregWeng
7. In this lesson you shall learn how to...
Bind this in Event handlers in the proper way
Deal with object properties w/ constructor & prototype
Extend instantiable object properly
Manage asynchronous flows with Promise
Write your first test case for a pure function
8. In this lesson you may also try to...
Avoid using closure when it shouldn't appear
Implement functions with closure when it's necessary
Write meaningful comments in JSDoc format
Make your code more expressive with map/forEach
9. About quizzes and the homework
We will refactor an example from scratch
Quizzes help you to think and learn things
They require you to add comments on several PR pages
Or, raise your hand
If you fail at homework they may save you, too
Homework will be marked strictly according to the public
marking criteria
That means, you either get passed or failed, no other
adjustments except the quizzes
10. Since I suppose you know this
class is not JavaScript tutorial
11. Questionnaire
Before the class begins, I would like to ask you if you know:
How to write constructor + prototype (instantiable object)
How to extend an object to add new methods
How to receive and dispatch events
What the 'this' may refer to?
What's a 'closure'?
What's the better way to control asynchronous flow
15. Some anti-patterns
You put all states in local variables
And then bind events with anonymous callbacks
And then encapsulate them as a 1K+ lines closure
And then try to create a "singleton" via a function that will be
invoked automatically when bootstrapping
And then make it as a Window Manager as Metacity of
Gnome or KWin of KDE
And then you shoot yourself in the foot
17. Beware of these terms
You put all states in local variables
And then bind events with anonymous callbacks
And then encapsulate them as a 1K+ lines closure
And then try to create a "singleton" via a function that will be
invoked automatically when bootstrapping
And then make it as a Window Manager as Metacity of
Gnome or KWin of KDE
And then you shoot yourself in the foot
class, private, flags, global objects, temporary variables
20. "The real badass Todo list"
"You want to write a Todo list,
and you feel it is a simple quest"
21. "The real badass Todo list"
"So you think, you only need to write several functions"
22. "The real badass Todo list"
"So you think, you only need to write several functions"
I have three little functions,
one is to draw the list,
one is to fetch the data,
and the last one is to save the data
23. "The real badass Todo list"
"So you think, you only need to write several functions"
http://bit.ly/1LeY5lv
28. Since we put all things globally
window
drawList fetchData saveData ...
29. Names and states may collide
window
drawList fetchData saveData ...
window
drawInput fetchData saveData ...
Working for the List
Working for the Input
36. It seems a successful solution to the issues...
Now we have two isolated parts of the program
People can work on that individually
There are no more tangled names and states
To those things like "singletons", closure looks a good
solution to disallow others create the instance twice
37. It seems a successful solution to the issues...
Now we have two isolated parts of the program
People can work on that individually
There are no more tangled names and states
To those things like "singletons", closure looks a good
solution to disallow others create the instance twice
Really?
38. Always think about these when you are coding
How do I test the function or instance?
Are these duplicated code necessary?
Could people reuse my code later on?
Is my solution the most expressive one?
Did I express the intention clearly?
40. Don't be intrigued by closure in such cases
You don't have any references for unit tests
If you really have some re-usable data or functions across
different parts, closures can't use them
That means, it's uneviable to write lots of duplicated
functions do the almost same thing
41. Don't be intrigued by closure in such cases
You don't have any references for unit tests
If you really have some re-usable data or functions across
different parts, closures can't use them
That means, it's uneviable to write lots of duplicated
functions do the almost same thing
However...
44. "Managers"
"You put all states in an object, and listen to all events and
hope everything will be fine"
TodoListManager
drawList fetchData saveData ...onItemAdded
user event
used by
The only "public" interface
45. Public interfaces of JavaScript program components
JavaScript components usually use handlers as public
interfaces among the user, server and other components
like to draw or to fire
new events
private helper
methods...
event handlers
server gateway
local data keeper
component
usernative events
server
sync
componentscustom events
46. So now we have
Managers that can keep queried elements and local data as
their states
TodoListManager
drawList fetchData saveData ...onItemAdded
user event
used by
The only "public" interface
47. And we're finally able to test our code
Unlike closure, we now have some references the test can
manipulate
48. About unit test
Right now, you don't need to figure out how it works
Just follow the structure and copy it
51. The globally "singleton" instance mess up tests
Consider what will happen when we load the files to test
such global object pattern
unit test for 'saveData'
save some dummy data
TodoListManager
do some tests
_listTodoItem (null)
_listTodoItem' (dummy)
unit test for 'drawList'
do some tests
(wrong)
53. The globally "singleton" instance mess up tests
With such patterns, we need to clear the dummy data and
other states made by previous tests
unit test for 'saveData'
save some dummy data
TodoListManager
do some tests
_listTodoItem (null)
_listTodoItem' (dummy)
unit test for 'drawList'
do some tests
(correct)
_listTodoItem' (null)
*reset it*
54. The globally "singleton" instance mess up tests
With such patterns, we need to clear the dummy data and
other states made by previous tests
And you barely know how to reset them properly if the
component is 1K+ lines long, and written by lots of people
In Gaia, this has happened countless times
And worse, people sometimes wrote tests rely on that: they
do some changes at the first test, and then use the
contaminated data to perform the next test
56. Test is good to you because...
There are lots of commits may change your code
57. Test is good to you because...
There are lots of commits may change your code
People will always screw you and your
code if you don't test them
58. Test is good to you because...
There are lots of commits may change your code
People will always screw you and your
code if you don't test them
We call these issues regressions
62. Test with instantiable objects
Create new instance when new test is performing
unit test for 'saveData'
save some dummy data
TodoListManager
do some tests
_listTodoItem (null)
_listTodoItem' (dummy)
unit test for 'drawList'
do some tests
TodoListManager
_listTodoItem (null)
63. The pattern
Design a constructor + prototype and then create instances
(constructor)
function
TodoListManager
TodoListManager.prototype
function start()
{...}
function drawList()
{...}
...
68. Constructor with effects
(constructor)
function
TodoListManager
We prefer to hold the instance before use it
(constructor)
function TodoListManager() {
this._wrapper = document.query...
this._listTodoItems = []
this.fetchData(...);
}
(create the instance & test it)
var instance = new TodoListManager();
// It will do fetching immediately,
// which is BAD
instance.drawList(...)
// Although we only want to test this
69. Constructor
(constructor)
function
TodoListManager
Put all initial effects in another function
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
...
(create the instance & test it)
var instance = new TodoListManager();
// It will do noththing now
instance.drawList(...)
// We can test this without deal with
// the effect we don't need
70. It means the shareable methods and data among instances
Prototype
(constructor)
function
TodoListManager(){
this.foo = [];
}
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
foo: [ ]
start() {}
foo: [ ]
start() {}
foo: [ ]
start() {}
foo: [ ]
start() {}
foo: [ ]
start() {}
(new instances)
71. So it's better to put data ONLY IN SETUP FUNCTIONS
Prototype
(constructor)
function
TodoListManager(){
}
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
start() {} start() {} start() {} start() {}
(wrong!)
foo: [ ]
foo: [ ]
start() {}
72. Every test can now modify the instance by their own needs
For tests
(constructor)
function
TodoListManager(){
this.foo = [];
}
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
foo: [1]
start() {}
foo: [ ]
start() {}
foo: [3,2]
start() {}
foo: null
start() {}
foo: {}
start() {}
(new instances)test #1 test #2 test #3 test #4
79. this
the owner
var SomeObject = {
foo: 3,
bar() {
console.log('Foo: ', this.foo);
}
}
SomeObject.bar();
// Will print "Foo:3"
80. this
the window
var SomeObject = {
foo: 3,
bar() {
console.log('Foo: ', this.foo);
}
}
var bar = SomeObject.bar;
// Will get reference to bar
bar();
// Will print "Foo:undefined"
// without binding and owner,
// the 'this' will become 'window'
81. this
the bound one
var SomeObject = {
foo: 3,
bar: (function() {
console.log('Foo: ', this.foo);
}).bind(SomeObject)
}
var bar = SomeObject.bar;
// Will get reference to bar
bar();
//
// since it's bound, the this will
// always be 'SomeObject'
82. You need to bind the 'this' if you use that
It is important since every time you put a callback...
83. Event handlers should follow the EventListener interface to
make a centralized dispatcher with the bound 'this'
It is important since every time you put a callback...
84. Event handlers should follow the EventListener interface to
make a centralized dispatcher with the bound 'this'
It is important since every time you put a callback...
93. new Promise(function(resolve, reject) {
// Do some async things.
// Then resolve it after done.
resolve();
// Or reject it due to the error.
reject();
}).then(function() {
// This function only executes after the
// previous step.
return [1,2,3];
}).then(function() {
// If return another Promise,
// the flow will stop here and only
// continue when the promise is resolved
return new Promise(function(r, c) {
setTimeout(r, 1000);
});
}).then(function() {
// This will not execute within the second
}).catch(function(error) {
// !IMPORTANT!
// Remember to catch Promise error in a
// function like this.
});
The Flow
94. Promise + Event Handler
|dispatchEvent| as the public interface to send message
|handleEvent| as the public interface to receive message
|Promise| to concat all steps of event handling
TodoListManager
drawList fetchData saveData ...onItemAdded
user event
organized by Promises
The only "public" interface
95. Promise + Event Handler
|dispatchEvent| as the public interface to send message
|handleEvent| as the public interface to receive message
|Promise| to concat all steps of event handling
handleEvent(event) {
switch(event.type) {
case 'todo-item-created':
var data = event.detail;
this.saveData(data)
.then(this.tidyUp.bind(this))
.then(...)
.then(...)
...
.catch(this.onError.bind(this))
}
}
96. Promise + Event Handler
Every asynchronous method should return a Promise to
allow we concating it, so we can eliminate all the callbacks
saveData() {
var promise = new Promise(function() {
...
};
return promise;
}
fetchData() {
var promise = new Promise(function() {
...
};
return promise;
}
98. Solve things in advance but native JavaScript ways
"class" (not ES6 class)
Don't try to copy them
Use "instantiable objects"
prototype + constructor
private
encapsulate
closure Use them very carefully and
wiselyanonymous functions
callback ** PROMISE ** (or beyond)
local variables As immutable as possible
global object Usually it means that you're
doing something really bad
Stop it and re-think the
whole case again
flags, temporary variables
singleton
99. Homework
1. Fork the Homework repo here
2. Fix all the issues in the code to refactor it
3. After that, make a git branch, commit, and then push it
4. Fire a Pull Request and set review to TAs and me
Remember: you can always ask any question at anytime
Don't struggle with any part you don't really understand
100. Homework: How to get points
You need at least address all the Tier 1 issues to get 4 points
You will get the extra 3 points from addressing Tier 2 issues
However, you will NOT get any points from the Tier 2,
if you fail to address ANY single issue of Tier 1
You need at least the 4 points from Tier 1 to pass this class
The extra points will benefit you in the following lessons
You can add or remove some code from the example.
However, make sure every change you make is with clear
intentions
101. Homework: Requirements (Tier 1)
Bind this in Event handlers
Deal with object properties w/ constructor & prototype
Deal with asynchronous flows with Promise
Write your first test case for a pure function (as the last test
of |test-list.js| file shows; for example, to test if |Math.sin|
works well as your assumption)
102. Homework: Requirements (Tier 2)
Implement functions with closure when it's necessary
Avoid using closure when it shouldn't appear (follow what
we taught in the class)
Write meaningful comments in JSDoc format
(reference: https://en.wikipedia.org/wiki/JSDoc#Example)