Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Understanding ScratchX Extensions with JavaScript

2,122 views

Published on

First of a two part slideshow that starts you off on the road towards building your own software extension blocks for the Scratch programming environment.

Notes: .
- Contains 39 slides.
- Aimed at experienced Scratch users/teachers with the motivation to learn more.
- Scratch is developed by the Lifelong Kindergarten Group at the MIT Media Lab. See http://scratch.mit.edu
- Please check back for occasional updates/errata.

Published in: Software
  • Just want to say THANK YOU for sharing this very detailed walk-through of this ScratchX extension. Brilliant work!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Understanding ScratchX Extensions with JavaScript

  1. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 22 added code to clear the poller same defined the blocks + url for info page almost the same; changed name
  23. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 37. 37 Methods taken from http://khanning.github.io/scratch-isstracker-extension/
  38. 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. 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

×