Atlanta Code Camp 2013

I just wrapped up speaking at Atlanta Code Camp! I spoke on the Modern Development Workflow, the acronym laden one we all are faced with today. Thanks to all who attended and super thanks to the conference organizers! They put on a great show with lots of talent present for sure!.

As I spoke of at the conference, I have uploaded all the code and slides. Since I covered GitHub in the talk, why not use GitHub? Yes! The link below will direct you to the code and slides. Shoot me a email if you got any questions! Cheers!

https://github.com/douglasknudsen/atlcodecamp2013

Update: The slides were dropped at https://speakerdeck.com/douglasknudsen/the-modern-web-workflow-the-acronym-inundation-edition as well.

Posted in CSS3, HTML5, JavaScript, Techy | Comments Off

AngularJS and a JS prototypal inheritance gotcha

Like many of you I’ve been shoring up my bits on AngularJS from Google. Really slick stuff that in short, extends HTML with attributes, something possible since well before HTML5: HTML5 Data Attributes. While watching a series of videos on Angular at http://egghead.io/ I came upon the title of ‘The Dot’ that addresses a rather popular seemingly buggy behavior. I cranked up a JSBin page for you to see the behavior and experiment http://jsbin.com/oviwan/2/edit

In short this is based on JavaScripts prototypal inheritance. Seems the above is very often considered a bug in AngularJS. You can get a full and deep description of things here The-Nuances-of-Scope-Prototypal-Inheritance

This whole topic got me to thinking about scope in AngularJS, not $scope, but scope. When you create a Angular fragment like the below, just what does scope mean and what is in scope? Because $scope is a bit of a important literal in AngularJS, this is rather hard to go and google.

Upon first gander, nothing unusual here, eh? The first ‘one’ section does some simple binding, the rest though all use the same model in name, data.message. These are all introduced on the same ‘level’ so to speak, but what’s the scope tree look like? Well, what do you think the behavior is of this small fragment? Check it out here http://jsbin.com/ibaded/1/edit

The first ‘one’ section is no surprise. Entering data in ‘two’, ‘three’, and ‘four’ is not surprising either. But wait! There’s more! Refresh and change the order, that is enter data in sections ‘four’, ‘three’, then ‘two’, see the difference? This is the prototype inheritance in action, but why? Scope! So, what how and where in Angular? Enter Batarang. Batarang is a nifty Chrome plugin for introspecting your Angular application. It is installed as a new tab on the developer tools window. So, grab the code at the JSBin link above and put it on your local host there, load it, and open up the dev tools, then nav to the AngularJS tab. You should see this sort of layout

batarang_one

This Batarang window is interactive, click ‘models’ to drill down and such. Click on ‘scope’ to be taken direct to the Elements tab in dev tools and have the element surrounding that scope be highlighted! Now, fill in the inputs top down and you should see this sort of information

Batarang_two

Now refresh and fill in the inputs backwards, bottom up. You should see the Batarang model displayed quite differently.

batarang_three

Why is this? It is due to the way JS works the prototype chain. Assignments of variables are immediate and happend within the current class. Reads however consult the current class, then recursively consult the prototype chain, in other words the parent classes until it is found. Thus a line like

var x = 5

will immediately assign 5 to x in the current scope. A line like

var foo = x

will incur a lookup through the chain, starting with the current scope. Couple this together like so

var data.message = “I am one”

and we see both a read and write in that order. The read of course consults the chain FIRST! if it finds data it uses it to create and assign message, where ever in the chain it was found. If JS does NOT find data, it then creates it where it stopped looking in the chain. Thus the behavior seen in the example!

There you have it. Though we are working using a descriptive tool such as Angular, its all JS still and we have to live by its rules. Using a tool like Batarang is immensely helpful in understanding the magic AngularJs provides.

For a Deep Read on protypical inheritance, check out this paper http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html

Posted in CSS3, HTML5, JavaScript, Techy, Universal Mind | Comments Off

Pi, Monte Carlo, and SVG fun with some requestAnimationFrame() thrown in

To dive into some performance research and testing, I needed a example that ran some JS loop action and created lots of nodes for your friend the DOM. Why not use a simple Pi approximation with a graphical representation? Enter Monte Carlo and ets find some Pi!

What is this Monte Carlo Method? AKA Monte Carlo Experiments comprise a set of methods using random sampling to arrive at a result. This method is good to use if its physically impossible say to try all combinations or in other case when the problem can not be worded in a closed form. The process is named after the casino. Seems the author’s uncle gambled at the Monte Carlo in NV quite a bit. Yes, Mathematics does have humor!

How to apply the Monte Carlo method to approximate Pi? Throw darts! Consider a dartboard inscribed in a square and consider the top right quadrant only. Assume its a unit circle and unit square as well. Randomly through n darts. By random, I mean random, no aiming! Find the ratio p of m/n where m is the number of darts landing inside the circle. This ratio approximates the area of the quarter circle.

Area = pi * r ^ 2, eh? Since its a unit circle, Area = pi. Throw in a 1/4 and thus we have an approximation!

Now for some code! My first stab at it is here dartPi.html and looks like this:

Monte Carlo One

Nice and red quarter circle there for ya. The Spinner graphic, also in SVG, is there as a performance indicator of sorts. If it stops spinning, your browser is blocked up. Go ahead and enter say a 1000 to test it out. Notice a slight pause in the spinner? Crank it up to 10000 and mash start. Yeah, nasty, eh? Oh by the way, it does not work so well on a iPhone, reader beware.

Enter requestAnimationFrame()! After some thought I realized that as I was throwing random darts, I was drawing them straight away. JS is fast. Create DOM nodes still pretty fast. Inserting DOM nodes with the browser taking over on each insert to try and render and paint these nodes, not so fast. In fact slow. requestAnimationFrame() Can help out here. What the heck is this cat? It tells the browser, hey dude, I want to animate something, go and do your repaint fun and call this call back when you are ready for me. This brings us to dartPi2.html

Take a look at how the approxPi( ) method was changed up. Instead of a simple for-loop, we now use requestAnimationFrame() to do our loop bidding. Go ahead and test this one out with 10000 darts! Note how the spinner keeps on spinning. Now this works smooth as silk, albeit slow, but has the added benefit of actually animating the darts individually. We could likely fiddle with things, say animate 10 or so darts per frame and still look good. Browsers and machines vary so greatly though, this is hazardous, so better to use some dynamic subset cardinality and determine when best to call requestAnimationFrame() to pass work on to the next frame. A green threading if you will.

The penultimate example dartPi3.html separates out some of the work a bit further to realize that the simple loop to generate the random dart positions is indeed fast and not noticeably blocking until the numbers are really high. The animations are removed as well. This of course exposes just how expensive it is to create the SVGDOM elements and insert them into the big old DOM tree.

Now we turn our sites onto a different approach in example four dartPi4.html As we saw previously, creating SVGDOM elements AND inserting them to the DOM iteratively is well, quite expensive. Would WebWorkers help perhaps? Lets see, the computational work is simply creating a simple array of cartesian data, nothing terribly taxing really at relatively low sample size, say < 500k or so. No much to gain with WebWorkers unless we go beyond those numbers, entirely possible if we want. What about the SVGDOM element creation? WebWorkers have no access to the DOM! oops. This leads us to knowing we can't use them for DOM manipulation either, all that is on the main mother thread. We are left with just tuning what we have and tweaking it.

Can we perhaps not create all the SVGDOM elements? Why sure! In example four I have done just that. Instead of creating the elements by hand, I instead just create one big fat string, a SVG document in fact, but not a DOM element as of yet. Then I just play the old el.innerHTML = myString game. Bamm! This sped things up quite a bit, only one re-render and re-paint phase to handle. But alas, at some point, say around 10k samples, you can start to see the pause. If you break out the console UI in your browser you should see the line I’m inserting into the DOM. This is logged just before setting the innerHTML property. You can get a idea just how long the re-rendering is taking.

So, we’ve played around a bit enjoying ourselves and learned a couple things, issues with performance of this or that and some cheap ways to address them. These ways are certainly not the solution to all life’s problems, there’s a towel for that, but they are useful in some use cases.

Happy trails!

DK

Posted in Blog, CSS3, HTML5, JavaScript, Techy, Universal Mind | Comments Off

SVG! What’s your vector Vector?

So, I got to playing with SVG in the old browser today. Amazing stuff can be had with this. SVG for the folks under that pet rock over in the corner is a acronym for Scalable Vector Graphics. Go ahead and mash that link to read up on what SVG is all about. The skinny: its all about the ‘scalable’ phrase.

As usual there’s some story and painful support issues, go figure. For the most part all your modern day browsers support SVG these days. ( yeah, so um, that does of course exclude IE ) Google even indexes SVG content. Huh? You didn’t read the WikiPedia link? Yeah, its text based goodness this SVG stuff. SVG files are basically a XML subset that can be rendered by whatever consumes it. Set your source free here. Here is a example that is resized to 100×100 for inline display, click it to open the same image at 100% of your browser view port. Go ahead and resize your browser to as big as you can. Notice no rastering or distortion, eh? Now ‘view source’in your browser and check out how its all whipped up. Also, note that the URL points direct to the SVG file and gets rendered. You can view source here too and see that the URL is the value passed to the src attribute. Pretty cool, eh? ( My wife says this image looks like rice, huh? Seems the Chinese character for rice is very similar. )

SVG Example

So that’s pretty swell and all, but what else can I do with this stuff? script it up! That is, I can create and manage SVG sources at runtime. This is done pretty much the same as with other DOM objects, with some slightly different syntax here and there. For my first example, I used a external SVG file loaded in at runtime and manipulated, well manipulated the positioning. Here is the SVG.

node.svg

You can load up a SVG source using Object, Embed, or iFrame even. All depends on your use-case there. I used Object this time around, which made positioning of the nodes in JS a little easier.

Check out the full source here EXAMPLE ONE

Next up I wanted to call a method on the SVG object and send it some data to respond to. WAIT! What? Oh yeah, cool idea eh? You can use JavaScript inside a SVG file! Lets check out what might be the ugliest SVG around here.

http://www.cubicleman.com/html5_play/svg/myNode.svg

View the source on that bad boy and see some JS like this…sweet eh?

Now, in the main HTML file loading this SVG, I simply add a onLoad handler, reach through the DOM and call this method passing the data I want

This technique could be useful for data driven SVG based UI controls, graphs, charts, etc.. Check out EXAMPE TWO

Both of the above exposed techniques to re-use the SVG source via using JS. Well, SVG already has this covered in itself by way of a couple tags: <defs> and <use>. Use the former tag to define your re-usable graphic resource and use the latter to well, use the resource.

Here you see a rectangle with a gradient fill is defined in the defs section. The graphic is NOT displayed in here. Further down you will see two use tags used. This is where the display actually occurs. Note that you can use the transform attribute to place the copy in different locations in the UI. fairly easy eh? Its a little bit tricker to use JS here. Here is a JS fragment of the action

Check out EXAMPLE THREE for some in depth coverage.

Of course no graphic manipulation examples should go with out a corporate directory example, but alas, I’ll forgo that and use a graph instead. A graph of the node and connection variety. In this case I created the SVG elements direct using code like

The above fragment indicates how I added soem rectangles. I used Math.rand() to randomly place these rectangles on screen. I stored all the nodes and x-y values in a array and used this to then draw lines from center to center. No weighted edges or anything here, just a simple example showing how simple this sort of thing is. Well, its as simple as the outcome! Check out EXAMPLE FOUR In reality, you would want to checkout D3 JS for a very robust data driven graphical library, but this simple approach could prove useful in your use-case.

Cheers!

Posted in CSS3, HTML5, JavaScript, Techy | Comments Off

Working with JS got you Hoisted?

SO I had a conversation with a co-worker DC Hoth today about some JS funkiness. Not a uncommon thing with JS, eh? Any how, we had this code snippet and at frist blush, looked so innocent. That notion was shattered rather abruptly. The sample went something like this:

On first gaze you’d think line 9 would spit out what? 1 right? wrongo! What is happening here is that JavaScript ‘hoists’ variable definitions up to the top of the function. This means that in reality the above looks like this:

How to avoid this? For one, ‘var scope’ your locals at the top of your function as a best practice. This will help with undefined issues. Note to self….

Posted in CSS3, Flex, HTML5, JavaScript | Comments Off