SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Understanding ScratchX
Extensions with JavaScript
© Darren Adkinson - 21 Jan 2016
Top-Down Learning
Approach Using A
Real World Example
Part 1 of 2
39 slides
V 1.4
2
T h e a u t h o r r e t a i n s
copyright of these slides.
You are free to use them so
long as the author’s name
i s q u o t e d o n a l l
presentations and excerpts.
ISS Tracker Scratch extension
code is provided with kind
permission of Kreg Hanning.
NOTE: occasional updates may be
p u b l i s h e d ( o n S l i d e S h a r e o r
elsewhere) from time to time.
Please check back for new versions.
Scratch is developed by the
Lifelong Kindergarten Group
at the MIT Media Lab.
See http://scratch.mit.edu
Scene Setting
Assumed you’re familiar with Scratch: https://scratch.mit.edu/about/
Not a “stand up & talk” presentation; meant to be worked through at
home.
You should have some JavaScript experience, or do some learning on
your own to get the most from this (see next slide).
Aimed at: keen Scratch students who want to learn more; motivated
teachers and parents.
These slides won’t get you all the way by any means, and they’re not
“follow-along-with-me”. They should be used alongside the ScratchX
wiki.
Who am I?
A systems engineer who makes complex stuff a little more understandable.
3
Where these slides can help
4
Your JavaScript knowledge
Understanding
ISS Tracker
Making your own
toy blocks
What these slides will help you with
What you should have already
Absolute
Beginner
Master
Entry Point
JS Entry Point is roughly:
- be familiar with most of the syntax
- understand if/else and for loops, basic constructs
- get a feeling for what functions and methods are
- write your own small programs
- read some simple code and understand (most) of it
It varies by person but a couple of hours a day
spread over 3 - 4 days would be a good start
Making your own
useful extension
What are Extensions?
They enable you to
create blocks that don’t
currently exist in
Scratch.
ScratchX.org hosts a
bunch of experimental
extensions that you can
play around with.
Divided into hardware
and software
extensions.
5
How will these slides work?
We’ll take a (gradual) deep dive into one
particular extension: ISS Tracker, by
Kreg Hanning.
The hard work is all Kreg’s. I just
happened to choose this extension to
teach myself and hopefully make the
topic more accessible to other people.
Just like Scratch, ScratchX makes code
open, though you’ll have to dig around a
little in your browser or on GitHub* to
find it.
6
*see next slide where I’ll discuss jump off points.
Complexity
Required
Future usefulness
0 25 50 75 100
git/
GitHub
“Jump Off Points (JoPs)”
The visual aspect of slides is great, but they’re linear and we can’t cover
everything.
I’ve highlighted “jump off points” throughout where it would be good for
you to go off and do some research/study on your own (or in your team!).
7
8
Complexity
Required
Future usefulness
0 25 50 75 100
The thing to go research.
There will usually be a web
link but don’t restrict your
self to that.
Totally
subjective
scale.
As it states. How hard is this
for a beginner? The higher the
number the less you should
worry if you don’t get it first or
even second time around.
How important is this
topic to learning how
ISS Tracker works (and
roughly, how to make
your own extension).
Moving away from ISS
Tracker and Scratch,
how useful is this topic
for general software
development, JavaScript
etc.
So this JoP means:
git/GitHub
- it has a learning curve - you’ll need to do a tutorial or two.
- you have to know some of it to make an extension.
- it’s *really* useful to know. Your time will not be wasted!
git/
GitHub
Recommend
you find and
take a
tutorial.
Don’t sweat
it. Just get a
rough feeling.
Example JoP
Let’s dive in
Go to http://scratchx.org/
#extensions. Find the ISS
Tracker extension and
open it by clicking on
“Sample Project”.
9
Have a play around and
see what it does. Most
of the blocks are regular
Scratch blocks, so you
should be able to get a
rough idea quite easily.
Complexity
Required
Future usefulness
0 50 100
ISS
Tracker
New Blocks
The “ISS” sprite uses two
custom-made blocks:
10
Note that both blocks have
some type of input facility for
the user.
Sprite1 only uses one
new block type: an
event block that is -
presumably - triggered
when the ISS passes
over a certain place.
11
New Blocks
So this “ISS Tracker” Scratch extension is a piece of code that creates three new
block types, and that’s it.
The Sample Project uses these three new blocks to track the ISS as it orbits
Earth. It makes sense to create a sample project every time you create new
blocks (there must have been some reason for creating them in the first place).
All of the code is contained in a single JavaScript file.
The ScratchX wiki is here: https://github.com/LLK/scratchx/wiki. I recommend
that you look at the FAQs first (scroll down) and then dig into the business end
later, as you go through these slides.
12
New Blocks
Complexity
Required
Future usefulness
(100%)
0 50 100
ScratchX
FAQ
ISS Extension Info
The extension developer will usually put
a web page on GitHub explaining
something about his/her extension.
Note that this is aimed primarily at end
users of the blocks, probably not so
much at people developing new
extensions.
This extension’s info page is here:
http://khanning.github.io/scratch-
isstracker-extension/
The quick way to get to this page (that
all extensions should provide) is by
clicking on the drop down arrow and
selecting “About XYZ extension…”
13
Complexity
Required
Future usefulness
(100% compare)
0 50 100
ISS About
page
14
Extension Relationships
For any extension we write there are a bunch of relationships to
think about. It looks complex but it’ll make more sense as you work
through the slides and Part Two.
ScratchXUser
Extension writer
ScratchX
wiki
reads
creates with
creates creates - via
extension .js file
Extension
info page
work
with
provides
support
for
reads / adds to / corrects
GitHub
loads extension .js file onto
reads
defines
hosts
writes
A
A
hosts
New blocks
.js file
The Extension Code
The ScratchX website itself doesn’t host the extension code. Instead the developer
puts it in a GitHub repository (an online store for software, mainly) and she/he tells
the ScratchX website where to get it from.
For now we can skip those details and just grab the extension code from our browser.
In your browser window that has ISS Tracker open up the Developer Tools or whatever
yours is called. Here I’ve used Chrome browser’s View -> Developer Tools option:
15
But, before we copy
the code into an
editor let’s take a
little diversion…
Dev tools
The developer tools can be intimidating as
they’re so powerful. This is also what makes
them great.
The Console tab is the most useful for us in
two ways: (1) we can play around with some
JavaScript at any time, and, more usefully
(2) it will show output from ISS Tracker if
the developer programmed his/her
extension that way.
16
Complexity
Required
Future usefulness
0 50 100
Browser
dev tools
(1)
17
Dev tools
Now try this so we can see the more useful stuff. Run the ISS Tracker
program and check that it’s working ok.
Bring up the dev tools and select “Console”.
Now turn off your wifi or pull your ethernet cable. Just make sure your
computer can’t connect to the web.
Wait a 30s or so and you should start seeing error messages appear like
these:
(2)
Some kind of error
message, clearly
console.log output
18
You don’t need to search for this
now but I’ve highlighted here
the part of Kreg’s code where he
specified this console.log output.
The function might look
inpenetrable right now but you
can get a rough idea that it’s
getting data about the ISS
from somewhere.
When you ‘pull the plug’ on your
internet connection it fails, and
throws up an error message.
Complexity
Required
Future usefulness
0 50 100
Get an
editor
A good code-aware text editor or Integrated
Development Environment will serve you well.
I’ve used Atom here; there are loads of free ones
out there.
Select the Sources tab and then navigate to the iss_extension.js file.
You can see the code right there in your dev tools window and it should be syntax color-
highlighted.
You can also find out where the code came from on a server if you mouseover the folder.
This is where your browser pulls it from. In our case it is at: https://
khanning.github.io/scratch-isstracker-extension/iss_extension.js. Put this in a new
browser tab and you can read it from there as well (plain black text, probably).
19
The Extension Code
Most of the
ScratchX files
are in here
We need this one
You can ignore the rest
20
iss_extension.js - skeleton
So the breakdown is:
(1) a comment block
(2) a bracketed ‘main’ function
(3) a bunch of var declarations
(4) three private functions
(5a) three block methods
(5b) two ‘internal’ methods
(6) an object called “descriptor”
(7) a call to ScratchExtensions.register
(8) a call to one of the private functions
(9) a var called poller that does something
(10) slightly weird looking closing of (2),
above
1
2
3
4
5a
6
7
8
9
10
5b
Many environments give you some code to start with,
“boilerplate”, “framework”, etc.
They often contain code you must use as well as some helpful code
that completes standard foundational tasks for you (‘automate
the boring stuff’).
The ScratchX wiki gives you some boilerplate that we’ll look at
next.
One way to start off when looking at someone else’s extension is
to see what they added on top of the boilerplate.
21
Boilerplate code
22
added code to clear the poller
same
defined the blocks + url for info page
almost the same; changed name
System methods
The boilerplate provides two methods that are meant to be ‘private’ and called by ScratchX
(hence they start with an underscore).*
“ext” is the name of our extension object so the notation ext._shutdown = etc essentially
means “add a function to our “ext” object and make it visible to other code” (this is roughly what
a method is: a function that you tell the world about).
ext._shutdown will be called by scratch_ext.js when it unregisters your code, for instance, if
you were to click on “Remove extension blocks”. This is where to put tidy up code.
ext._getStatus will be called by scratch_ext.js if it needs to get the status of your plugin
(more relevant to hardware than software plugins).
23
*There is a subtle distinction here since all the methods will only be called within
ScratchX. The difference is that the block methods will be indirectly called by the
ScratchX application programmer when he/she uses the new blocks, whereas these
two underscore methods will only potentially be called by the ScratchX environment.
The descriptor object
24
url for info page
any drop down menus
that our blocks will use
Op Code ie.
block type
formatted
block label method name
optional default
argument values
%s - replace with string
%m.<menu> - replace with choice from the ‘menus’ list
The ScratchX wiki
covers this quite well.
Some words about IIFEs
25
The extension code is all contained within a bracketed function expression.
This pattern is called an Immediately Invoked Function Expression (IIFE).
The brackets (parentheses) are to trick the JS engine into treating the
function as an expression so that it will be immediately invoked (ie. run).
It’s not a regular function statement that sits around until called upon.
The main reason for doing this is to shield all of our variables from being in
the global space - so they don’t clash with someone else’s variables.
code goes here
There are two common ways to lay this out:
A. ( function (<optional params>) { code } ) (<optional arguments>);
B. ( function (<optional params>) { code } (<optional arguments>) );
26
A. ( function (<optional params>) { code } ) (<optional arguments>);
B. ( function (<optional params>) { code } (<optional arguments>) );
Some words about IIFEs
code goes here
ScratchX uses the type A, but A and B are equivalent.
The green parens are the ‘wrappers’ that make the whole function act like an
expression.
The function expects a parameter, called “ext” (this is the extension object)
We supply the function with a starting argument, which is an empty object.
The ‘ {} ‘ stands for an empty object in JS.
Block types
27
ISS Tracker uses three different types of block: a Hat block (h), an Asynchronous
reporter (R), and a Synchronous reporter (r).
Anything that runs synchronously means it could delay your whole function if you
don’t write it correctly or use it in the wrong place.
You should NOT use a synchronous block for anything that will take more than a
few milliseconds or will need to wait on some external source.
When we look at the specific methods in Part Two this will make more sense.
This code shows how we register our extension with ScratchX.
This is quite straightforward: just make sure your extension name is unique.
Here’s an example from a different extension (Xi Client, by Alan Yorinks):
28
Register our extension
Our extension name The descriptor object Our extension object
You can see that it’s highly unlikely anyone else would write an extension with the
same name. This makes it possible to have two or more extensions loaded within
ScratchX at the same time.
The .register call
29
lib.register = function (name, descriptor, handler, deviceSpec) {
if (name in handlers) {
console.log('Scratch extension "' + name + '" already exists!');
return false;
}
… more code here
};
You really don’t need to know this but when you call ScratchExtensions.register() the
method you’re calling is listed at http://scratchx.org/scratch_extensions/scratch_ext.js
Only hardware extensions
provide a deviceSpec
As we said earlier, ScratchX won’t let you load an extension if it has the same name
as an extension that you’re already using. Here I changed my test extension to be
called “ISS Tracker” and tried to load it when I had the real ISS Tracker running:
30
Checkpoint
We’ve more or less covered the greyed out
areas.
What is left is the meat of this code.
We’ll handle the easy stuff first and do a
quick overview of the more complex stuff.
Part Two will cover (4) and (5a) in more
detail.
1
2
3
4
5a
6
7
8
9
10
5b
Variables
31
3
This is quite straightforward: two constants (or at least variables that are not
meant to be changed in any way - the convention is to capitalize them).
An empty object called “locations”. (Note that objects can contain nested objects,
arrays etc, so we simply don’t know yet how complex this object may end up being).
A variable called issData that has no value right now (we don’t know what type it
is).
These are available within our code but can’t be accessed by, and won’t clash with,
anyone outside - since our code is all wrapped inside a special type of function (see
earlier slides on IIFE).
Entry point
32
When our function loads it runs straight away, but what exactly runs?
First: it registers itself with ScratchX, as we’ve seen earlier.
Next it makes a call to its own function, updateISSLocation().
Then it declares a variable called poller and sets it off on its repeating task.
So where does “setInterval” come from? The three main choices are: (1) Kreg wrote it,
(2) it’s built in to the language, (3) it’s part of ScratchX or a library that ScratchX
uses.
setInterval()
33
If you’re not sure the simplest thing to do is google it and see what comes up. This one
is a built in method.
Normally I’d go to the MDN (Mozilla Developer Network) website, but in this case I
think W3Schools has a better explanation.
We get access to this method because we’re running in an open window.
setInterval calls the function updateISSLocation every (approx.) 2000 milliseconds
- which is every 2 seconds.
We don’t have to explicitly say window.setInterval(). Just setInterval() will work.
34
setInterval()
setup a timer to call this function
roughly every 2s
until someone clears the interval
Remember the _shutdown method of
our ext object? That’s where the timer is
cancelled.
Complexity
Required
Future usefulness
0 50 100
MDN &
W3Schools
Get used to going online to
look up syntax, methods,
examples, etc.
Mozilla Developer Network
(MDN) is recommended.
35
Checkpoint
A quick blast through the internal
functions (4) and the methods (5a) and
we’re pretty much done for Part One.
1
2
3
4
5a
6
7
8
9
10
5b
36
Internal functions
Roughly - what it does
- Queries a server to get lat / long etc for a
specific place (initially Boston, Ma).
- Build up a locations object for each place
the user inputs.
How complex
(relatively)
- Queries a server to find out where the
International Space Station is.
- Helper function for the distanceFrom
method. This is where the Haversine
formula (see next slide) is actually used.
37
Methods
taken from http://khanning.github.io/scratch-isstracker-extension/
38
Checkpoint
That’s it for Part One. Part Two will cover: deeper dive into the methods and internal
functions; tips on how to set up your own test extension - sections 2 and 4 from the
ScratchX wiki; thoughts about what (software) extensions to make.
We covered quite a lot of 3.i and 3.ii from the wiki. (Part 3.iii won’t be covered as these
slides are about software extensions.)
Complexity
Required
Future usefulness
(100%)
0 50 100
ScratchX
wiki
Hope this was helpful.
Part 2 will be out sometime in Feb 2016.
Constructive comments, ideas, suggestions, corrections, etc are welcome.
GitHub username: darren-a
Email: dadkinson@gmail.com
39
Wrap Up
What extensions would you like to write?
How does the reverse-engineered, top-down learning approach suit you?
Would you be interested in learning JavaScript by taking real world code and deconstructing it like this?
Questions for you

Weitere ähnliche Inhalte

Was ist angesagt?

232 md5-considered-harmful-slides
232 md5-considered-harmful-slides232 md5-considered-harmful-slides
232 md5-considered-harmful-slides
Dan Kaminsky
 
Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2
ice799
 

Was ist angesagt? (20)

PyParis 2017 / Pandas - What's new and whats coming - Joris van den Bossche
PyParis 2017 / Pandas - What's new and whats coming - Joris van den BosschePyParis 2017 / Pandas - What's new and whats coming - Joris van den Bossche
PyParis 2017 / Pandas - What's new and whats coming - Joris van den Bossche
 
Racing with Droids
Racing with DroidsRacing with Droids
Racing with Droids
 
Security research over Windows #defcon china
Security research over Windows #defcon chinaSecurity research over Windows #defcon china
Security research over Windows #defcon china
 
232 md5-considered-harmful-slides
232 md5-considered-harmful-slides232 md5-considered-harmful-slides
232 md5-considered-harmful-slides
 
Writing malware while the blue team is staring at you
Writing malware while the blue team is staring at youWriting malware while the blue team is staring at you
Writing malware while the blue team is staring at you
 
[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015
 
Bugs from Outer Space | while42 SF #6
Bugs from Outer Space | while42 SF #6Bugs from Outer Space | while42 SF #6
Bugs from Outer Space | while42 SF #6
 
Process Doppelgänging
Process Doppelgänging Process Doppelgänging
Process Doppelgänging
 
Puppet Camp LA 2/19/2015
Puppet Camp LA 2/19/2015Puppet Camp LA 2/19/2015
Puppet Camp LA 2/19/2015
 
Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017Invoke-Obfuscation nullcon 2017
Invoke-Obfuscation nullcon 2017
 
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
50 Shades of Fuzzing by Peter Hlavaty & Marco Grassi
 
Us 16-subverting apple-graphics_practical_approaches_to_remotely_gaining_root...
Us 16-subverting apple-graphics_practical_approaches_to_remotely_gaining_root...Us 16-subverting apple-graphics_practical_approaches_to_remotely_gaining_root...
Us 16-subverting apple-graphics_practical_approaches_to_remotely_gaining_root...
 
Docker: automation for the rest of us
Docker: automation for the rest of usDocker: automation for the rest of us
Docker: automation for the rest of us
 
Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2
 
So You Want To Write Your Own Benchmark
So You Want To Write Your Own BenchmarkSo You Want To Write Your Own Benchmark
So You Want To Write Your Own Benchmark
 
Abusing Microsoft Kerberos - Sorry you guys don't get it
Abusing Microsoft Kerberos - Sorry you guys don't get itAbusing Microsoft Kerberos - Sorry you guys don't get it
Abusing Microsoft Kerberos - Sorry you guys don't get it
 
Go & multi platform GUI Trials and Errors
Go & multi platform GUI Trials and ErrorsGo & multi platform GUI Trials and Errors
Go & multi platform GUI Trials and Errors
 
Pentester++
Pentester++Pentester++
Pentester++
 
Nullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk throughNullcon Hack IM 2011 walk through
Nullcon Hack IM 2011 walk through
 

Andere mochten auch

mkombe munga cv use
mkombe munga cv usemkombe munga cv use
mkombe munga cv use
mkombe munga
 
Sample Work (Feature Article)
Sample Work (Feature Article)Sample Work (Feature Article)
Sample Work (Feature Article)
Mackenzie Jordan
 
Sandra Fratticci - articoli Culturalazio
Sandra Fratticci - articoli CulturalazioSandra Fratticci - articoli Culturalazio
Sandra Fratticci - articoli Culturalazio
Sandra Fratticci
 
Green Fish Proposal V6 DC
Green Fish Proposal V6 DCGreen Fish Proposal V6 DC
Green Fish Proposal V6 DC
David Cooper
 
Niki Calderone UX Research Portfolio
Niki Calderone UX Research PortfolioNiki Calderone UX Research Portfolio
Niki Calderone UX Research Portfolio
Niki Calderone Canton
 

Andere mochten auch (14)

Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
 
mkombe munga cv use
mkombe munga cv usemkombe munga cv use
mkombe munga cv use
 
Apache SystemML 2016 Summer class primer by Berthold Reinwald
Apache SystemML 2016 Summer class primer by Berthold ReinwaldApache SystemML 2016 Summer class primer by Berthold Reinwald
Apache SystemML 2016 Summer class primer by Berthold Reinwald
 
Sample Work (Feature Article)
Sample Work (Feature Article)Sample Work (Feature Article)
Sample Work (Feature Article)
 
Remodelación de París y eclecticismo
Remodelación de París y eclecticismoRemodelación de París y eclecticismo
Remodelación de París y eclecticismo
 
New Items - Constellation 2017
New Items - Constellation 2017New Items - Constellation 2017
New Items - Constellation 2017
 
Type cast operator
Type cast operatorType cast operator
Type cast operator
 
018 4895 healing for loved ones
018 4895 healing for loved ones018 4895 healing for loved ones
018 4895 healing for loved ones
 
04course reg uc_model_rpt (1)
04course reg uc_model_rpt (1)04course reg uc_model_rpt (1)
04course reg uc_model_rpt (1)
 
018 4877 power your life 0
018 4877 power your life 0018 4877 power your life 0
018 4877 power your life 0
 
Sandra Fratticci - articoli Culturalazio
Sandra Fratticci - articoli CulturalazioSandra Fratticci - articoli Culturalazio
Sandra Fratticci - articoli Culturalazio
 
Tabla Salarial-Construcción civil- Peru
Tabla Salarial-Construcción civil- PeruTabla Salarial-Construcción civil- Peru
Tabla Salarial-Construcción civil- Peru
 
Green Fish Proposal V6 DC
Green Fish Proposal V6 DCGreen Fish Proposal V6 DC
Green Fish Proposal V6 DC
 
Niki Calderone UX Research Portfolio
Niki Calderone UX Research PortfolioNiki Calderone UX Research Portfolio
Niki Calderone UX Research Portfolio
 

Ähnlich wie Understanding ScratchX Extensions with JavaScript

Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
Katy Allen
 
Building an Open Source iOS app: lessons learned
Building an Open Source iOS app: lessons learnedBuilding an Open Source iOS app: lessons learned
Building an Open Source iOS app: lessons learned
Wojciech Koszek
 
Your java script library
Your java script libraryYour java script library
Your java script library
jasfog
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]
RootedCON
 

Ähnlich wie Understanding ScratchX Extensions with JavaScript (20)

Hacking the Kinect with GAFFTA Day 1
Hacking the Kinect with GAFFTA Day 1Hacking the Kinect with GAFFTA Day 1
Hacking the Kinect with GAFFTA Day 1
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
 
Building an Open Source iOS app: lessons learned
Building an Open Source iOS app: lessons learnedBuilding an Open Source iOS app: lessons learned
Building an Open Source iOS app: lessons learned
 
Six reasons to learn JavaScript
Six reasons to learn JavaScriptSix reasons to learn JavaScript
Six reasons to learn JavaScript
 
Open frameworks 101_fitc
Open frameworks 101_fitcOpen frameworks 101_fitc
Open frameworks 101_fitc
 
Lunch and learn as3_frameworks
Lunch and learn as3_frameworksLunch and learn as3_frameworks
Lunch and learn as3_frameworks
 
scratch-3-tutorial.pdf
scratch-3-tutorial.pdfscratch-3-tutorial.pdf
scratch-3-tutorial.pdf
 
Need 4 Speed FI
Need 4 Speed FINeed 4 Speed FI
Need 4 Speed FI
 
Writing native Linux desktop apps with JavaScript
Writing native Linux desktop apps with JavaScriptWriting native Linux desktop apps with JavaScript
Writing native Linux desktop apps with JavaScript
 
Your java script library
Your java script libraryYour java script library
Your java script library
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
 
Reactive datastore demo (2020 03-21)
Reactive datastore demo (2020 03-21)Reactive datastore demo (2020 03-21)
Reactive datastore demo (2020 03-21)
 
Introduction to Box2D Physics Engine
Introduction to Box2D Physics EngineIntroduction to Box2D Physics Engine
Introduction to Box2D Physics Engine
 
Survive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and TricksSurvive JavaScript - Strategies and Tricks
Survive JavaScript - Strategies and Tricks
 
Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3
 
mblock_extension_guide.pdf
mblock_extension_guide.pdfmblock_extension_guide.pdf
mblock_extension_guide.pdf
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]
 
Cpb2010
Cpb2010Cpb2010
Cpb2010
 
War of the Machines: PVS-Studio vs. TensorFlow
War of the Machines: PVS-Studio vs. TensorFlowWar of the Machines: PVS-Studio vs. TensorFlow
War of the Machines: PVS-Studio vs. TensorFlow
 
3stages Wdn08 V3
3stages Wdn08 V33stages Wdn08 V3
3stages Wdn08 V3
 

Kürzlich hochgeladen

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Kürzlich hochgeladen (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 

Understanding ScratchX Extensions with JavaScript

  • 1. Understanding ScratchX Extensions with JavaScript © Darren Adkinson - 21 Jan 2016 Top-Down Learning Approach Using A Real World Example Part 1 of 2 39 slides V 1.4
  • 2. 2 T h e a u t h o r r e t a i n s copyright of these slides. You are free to use them so long as the author’s name i s q u o t e d o n a l l presentations and excerpts. ISS Tracker Scratch extension code is provided with kind permission of Kreg Hanning. NOTE: occasional updates may be p u b l i s h e d ( o n S l i d e S h a r e o r elsewhere) from time to time. Please check back for new versions. Scratch is developed by the Lifelong Kindergarten Group at the MIT Media Lab. See http://scratch.mit.edu
  • 3. Scene Setting Assumed you’re familiar with Scratch: https://scratch.mit.edu/about/ Not a “stand up & talk” presentation; meant to be worked through at home. You should have some JavaScript experience, or do some learning on your own to get the most from this (see next slide). Aimed at: keen Scratch students who want to learn more; motivated teachers and parents. These slides won’t get you all the way by any means, and they’re not “follow-along-with-me”. They should be used alongside the ScratchX wiki. Who am I? A systems engineer who makes complex stuff a little more understandable. 3
  • 4. Where these slides can help 4 Your JavaScript knowledge Understanding ISS Tracker Making your own toy blocks What these slides will help you with What you should have already Absolute Beginner Master Entry Point JS Entry Point is roughly: - be familiar with most of the syntax - understand if/else and for loops, basic constructs - get a feeling for what functions and methods are - write your own small programs - read some simple code and understand (most) of it It varies by person but a couple of hours a day spread over 3 - 4 days would be a good start Making your own useful extension
  • 5. What are Extensions? They enable you to create blocks that don’t currently exist in Scratch. ScratchX.org hosts a bunch of experimental extensions that you can play around with. Divided into hardware and software extensions. 5
  • 6. How will these slides work? We’ll take a (gradual) deep dive into one particular extension: ISS Tracker, by Kreg Hanning. The hard work is all Kreg’s. I just happened to choose this extension to teach myself and hopefully make the topic more accessible to other people. Just like Scratch, ScratchX makes code open, though you’ll have to dig around a little in your browser or on GitHub* to find it. 6 *see next slide where I’ll discuss jump off points.
  • 7. Complexity Required Future usefulness 0 25 50 75 100 git/ GitHub “Jump Off Points (JoPs)” The visual aspect of slides is great, but they’re linear and we can’t cover everything. I’ve highlighted “jump off points” throughout where it would be good for you to go off and do some research/study on your own (or in your team!). 7
  • 8. 8 Complexity Required Future usefulness 0 25 50 75 100 The thing to go research. There will usually be a web link but don’t restrict your self to that. Totally subjective scale. As it states. How hard is this for a beginner? The higher the number the less you should worry if you don’t get it first or even second time around. How important is this topic to learning how ISS Tracker works (and roughly, how to make your own extension). Moving away from ISS Tracker and Scratch, how useful is this topic for general software development, JavaScript etc. So this JoP means: git/GitHub - it has a learning curve - you’ll need to do a tutorial or two. - you have to know some of it to make an extension. - it’s *really* useful to know. Your time will not be wasted! git/ GitHub Recommend you find and take a tutorial. Don’t sweat it. Just get a rough feeling. Example JoP
  • 9. Let’s dive in Go to http://scratchx.org/ #extensions. Find the ISS Tracker extension and open it by clicking on “Sample Project”. 9 Have a play around and see what it does. Most of the blocks are regular Scratch blocks, so you should be able to get a rough idea quite easily. Complexity Required Future usefulness 0 50 100 ISS Tracker
  • 10. New Blocks The “ISS” sprite uses two custom-made blocks: 10 Note that both blocks have some type of input facility for the user.
  • 11. Sprite1 only uses one new block type: an event block that is - presumably - triggered when the ISS passes over a certain place. 11 New Blocks
  • 12. So this “ISS Tracker” Scratch extension is a piece of code that creates three new block types, and that’s it. The Sample Project uses these three new blocks to track the ISS as it orbits Earth. It makes sense to create a sample project every time you create new blocks (there must have been some reason for creating them in the first place). All of the code is contained in a single JavaScript file. The ScratchX wiki is here: https://github.com/LLK/scratchx/wiki. I recommend that you look at the FAQs first (scroll down) and then dig into the business end later, as you go through these slides. 12 New Blocks Complexity Required Future usefulness (100%) 0 50 100 ScratchX FAQ
  • 13. ISS Extension Info The extension developer will usually put a web page on GitHub explaining something about his/her extension. Note that this is aimed primarily at end users of the blocks, probably not so much at people developing new extensions. This extension’s info page is here: http://khanning.github.io/scratch- isstracker-extension/ The quick way to get to this page (that all extensions should provide) is by clicking on the drop down arrow and selecting “About XYZ extension…” 13 Complexity Required Future usefulness (100% compare) 0 50 100 ISS About page
  • 14. 14 Extension Relationships For any extension we write there are a bunch of relationships to think about. It looks complex but it’ll make more sense as you work through the slides and Part Two. ScratchXUser Extension writer ScratchX wiki reads creates with creates creates - via extension .js file Extension info page work with provides support for reads / adds to / corrects GitHub loads extension .js file onto reads defines hosts writes A A hosts New blocks .js file
  • 15. The Extension Code The ScratchX website itself doesn’t host the extension code. Instead the developer puts it in a GitHub repository (an online store for software, mainly) and she/he tells the ScratchX website where to get it from. For now we can skip those details and just grab the extension code from our browser. In your browser window that has ISS Tracker open up the Developer Tools or whatever yours is called. Here I’ve used Chrome browser’s View -> Developer Tools option: 15 But, before we copy the code into an editor let’s take a little diversion…
  • 16. Dev tools The developer tools can be intimidating as they’re so powerful. This is also what makes them great. The Console tab is the most useful for us in two ways: (1) we can play around with some JavaScript at any time, and, more usefully (2) it will show output from ISS Tracker if the developer programmed his/her extension that way. 16 Complexity Required Future usefulness 0 50 100 Browser dev tools (1)
  • 17. 17 Dev tools Now try this so we can see the more useful stuff. Run the ISS Tracker program and check that it’s working ok. Bring up the dev tools and select “Console”. Now turn off your wifi or pull your ethernet cable. Just make sure your computer can’t connect to the web. Wait a 30s or so and you should start seeing error messages appear like these: (2) Some kind of error message, clearly console.log output
  • 18. 18 You don’t need to search for this now but I’ve highlighted here the part of Kreg’s code where he specified this console.log output. The function might look inpenetrable right now but you can get a rough idea that it’s getting data about the ISS from somewhere. When you ‘pull the plug’ on your internet connection it fails, and throws up an error message. Complexity Required Future usefulness 0 50 100 Get an editor A good code-aware text editor or Integrated Development Environment will serve you well. I’ve used Atom here; there are loads of free ones out there.
  • 19. Select the Sources tab and then navigate to the iss_extension.js file. You can see the code right there in your dev tools window and it should be syntax color- highlighted. You can also find out where the code came from on a server if you mouseover the folder. This is where your browser pulls it from. In our case it is at: https:// khanning.github.io/scratch-isstracker-extension/iss_extension.js. Put this in a new browser tab and you can read it from there as well (plain black text, probably). 19 The Extension Code Most of the ScratchX files are in here We need this one You can ignore the rest
  • 20. 20 iss_extension.js - skeleton So the breakdown is: (1) a comment block (2) a bracketed ‘main’ function (3) a bunch of var declarations (4) three private functions (5a) three block methods (5b) two ‘internal’ methods (6) an object called “descriptor” (7) a call to ScratchExtensions.register (8) a call to one of the private functions (9) a var called poller that does something (10) slightly weird looking closing of (2), above 1 2 3 4 5a 6 7 8 9 10 5b
  • 21. Many environments give you some code to start with, “boilerplate”, “framework”, etc. They often contain code you must use as well as some helpful code that completes standard foundational tasks for you (‘automate the boring stuff’). The ScratchX wiki gives you some boilerplate that we’ll look at next. One way to start off when looking at someone else’s extension is to see what they added on top of the boilerplate. 21 Boilerplate code
  • 22. 22 added code to clear the poller same defined the blocks + url for info page almost the same; changed name
  • 23. System methods The boilerplate provides two methods that are meant to be ‘private’ and called by ScratchX (hence they start with an underscore).* “ext” is the name of our extension object so the notation ext._shutdown = etc essentially means “add a function to our “ext” object and make it visible to other code” (this is roughly what a method is: a function that you tell the world about). ext._shutdown will be called by scratch_ext.js when it unregisters your code, for instance, if you were to click on “Remove extension blocks”. This is where to put tidy up code. ext._getStatus will be called by scratch_ext.js if it needs to get the status of your plugin (more relevant to hardware than software plugins). 23 *There is a subtle distinction here since all the methods will only be called within ScratchX. The difference is that the block methods will be indirectly called by the ScratchX application programmer when he/she uses the new blocks, whereas these two underscore methods will only potentially be called by the ScratchX environment.
  • 24. The descriptor object 24 url for info page any drop down menus that our blocks will use Op Code ie. block type formatted block label method name optional default argument values %s - replace with string %m.<menu> - replace with choice from the ‘menus’ list The ScratchX wiki covers this quite well.
  • 25. Some words about IIFEs 25 The extension code is all contained within a bracketed function expression. This pattern is called an Immediately Invoked Function Expression (IIFE). The brackets (parentheses) are to trick the JS engine into treating the function as an expression so that it will be immediately invoked (ie. run). It’s not a regular function statement that sits around until called upon. The main reason for doing this is to shield all of our variables from being in the global space - so they don’t clash with someone else’s variables. code goes here There are two common ways to lay this out: A. ( function (<optional params>) { code } ) (<optional arguments>); B. ( function (<optional params>) { code } (<optional arguments>) );
  • 26. 26 A. ( function (<optional params>) { code } ) (<optional arguments>); B. ( function (<optional params>) { code } (<optional arguments>) ); Some words about IIFEs code goes here ScratchX uses the type A, but A and B are equivalent. The green parens are the ‘wrappers’ that make the whole function act like an expression. The function expects a parameter, called “ext” (this is the extension object) We supply the function with a starting argument, which is an empty object. The ‘ {} ‘ stands for an empty object in JS.
  • 27. Block types 27 ISS Tracker uses three different types of block: a Hat block (h), an Asynchronous reporter (R), and a Synchronous reporter (r). Anything that runs synchronously means it could delay your whole function if you don’t write it correctly or use it in the wrong place. You should NOT use a synchronous block for anything that will take more than a few milliseconds or will need to wait on some external source. When we look at the specific methods in Part Two this will make more sense.
  • 28. This code shows how we register our extension with ScratchX. This is quite straightforward: just make sure your extension name is unique. Here’s an example from a different extension (Xi Client, by Alan Yorinks): 28 Register our extension Our extension name The descriptor object Our extension object You can see that it’s highly unlikely anyone else would write an extension with the same name. This makes it possible to have two or more extensions loaded within ScratchX at the same time.
  • 29. The .register call 29 lib.register = function (name, descriptor, handler, deviceSpec) { if (name in handlers) { console.log('Scratch extension "' + name + '" already exists!'); return false; } … more code here }; You really don’t need to know this but when you call ScratchExtensions.register() the method you’re calling is listed at http://scratchx.org/scratch_extensions/scratch_ext.js Only hardware extensions provide a deviceSpec As we said earlier, ScratchX won’t let you load an extension if it has the same name as an extension that you’re already using. Here I changed my test extension to be called “ISS Tracker” and tried to load it when I had the real ISS Tracker running:
  • 30. 30 Checkpoint We’ve more or less covered the greyed out areas. What is left is the meat of this code. We’ll handle the easy stuff first and do a quick overview of the more complex stuff. Part Two will cover (4) and (5a) in more detail. 1 2 3 4 5a 6 7 8 9 10 5b
  • 31. Variables 31 3 This is quite straightforward: two constants (or at least variables that are not meant to be changed in any way - the convention is to capitalize them). An empty object called “locations”. (Note that objects can contain nested objects, arrays etc, so we simply don’t know yet how complex this object may end up being). A variable called issData that has no value right now (we don’t know what type it is). These are available within our code but can’t be accessed by, and won’t clash with, anyone outside - since our code is all wrapped inside a special type of function (see earlier slides on IIFE).
  • 32. Entry point 32 When our function loads it runs straight away, but what exactly runs? First: it registers itself with ScratchX, as we’ve seen earlier. Next it makes a call to its own function, updateISSLocation(). Then it declares a variable called poller and sets it off on its repeating task. So where does “setInterval” come from? The three main choices are: (1) Kreg wrote it, (2) it’s built in to the language, (3) it’s part of ScratchX or a library that ScratchX uses.
  • 33. setInterval() 33 If you’re not sure the simplest thing to do is google it and see what comes up. This one is a built in method. Normally I’d go to the MDN (Mozilla Developer Network) website, but in this case I think W3Schools has a better explanation. We get access to this method because we’re running in an open window. setInterval calls the function updateISSLocation every (approx.) 2000 milliseconds - which is every 2 seconds. We don’t have to explicitly say window.setInterval(). Just setInterval() will work.
  • 34. 34 setInterval() setup a timer to call this function roughly every 2s until someone clears the interval Remember the _shutdown method of our ext object? That’s where the timer is cancelled. Complexity Required Future usefulness 0 50 100 MDN & W3Schools Get used to going online to look up syntax, methods, examples, etc. Mozilla Developer Network (MDN) is recommended.
  • 35. 35 Checkpoint A quick blast through the internal functions (4) and the methods (5a) and we’re pretty much done for Part One. 1 2 3 4 5a 6 7 8 9 10 5b
  • 36. 36 Internal functions Roughly - what it does - Queries a server to get lat / long etc for a specific place (initially Boston, Ma). - Build up a locations object for each place the user inputs. How complex (relatively) - Queries a server to find out where the International Space Station is. - Helper function for the distanceFrom method. This is where the Haversine formula (see next slide) is actually used.
  • 38. 38 Checkpoint That’s it for Part One. Part Two will cover: deeper dive into the methods and internal functions; tips on how to set up your own test extension - sections 2 and 4 from the ScratchX wiki; thoughts about what (software) extensions to make. We covered quite a lot of 3.i and 3.ii from the wiki. (Part 3.iii won’t be covered as these slides are about software extensions.) Complexity Required Future usefulness (100%) 0 50 100 ScratchX wiki
  • 39. Hope this was helpful. Part 2 will be out sometime in Feb 2016. Constructive comments, ideas, suggestions, corrections, etc are welcome. GitHub username: darren-a Email: dadkinson@gmail.com 39 Wrap Up What extensions would you like to write? How does the reverse-engineered, top-down learning approach suit you? Would you be interested in learning JavaScript by taking real world code and deconstructing it like this? Questions for you