Facades, Repositories, and Model-View-Whatever

This week, in a couple different contexts, I saw the debate emerge as to whether or not an application’s UI can be developed prior to the data end-points it requires being available or finished. While obviously the completed end-to-end application cannot be finished, I see no reason why any UI, following any MV* pattern, cannot be completed independent of it’s data dependencies. By completion I mean rendering, input validation, and error handling related to all CRUD operations; as well as all concomitant unit tests. I also think this can be done even without any initial agreement on the end-points’ contracts, and whether the data is simple or complex. And I think it can be done easily with modern design patterns, and that the majority of people would agree with me and find it obvious. All that is required is an agreed upon specification or acceptance criteria that both the front-end and mid-tier developers adhere to.

Anyone doing UI development following a MV* (model-view-“whatever”) pattern can define a view-model that represents the data the UI tier receives from the mid-tier for rendering, or the data the UI submits to the mid-tier. This view-model can be a facade of any models defined in the mid-tier and need not map exactly to any one mid-tier model. For that matter, so long as the acceptance criteria is well-defined, we need not know how the mid-tier developer is going to define his models. Let’s call our view-model MyViewModel. MyViewModel will contain an identifier property that is also a facade, and let’s say we define it to be of type MyViewModelId. This allows it to be any primitive, composite or custom type.

Following from that, the UI developer can define an interface something like the following:

interface IDataRepository
{
    MyViewModelId Create(MyViewModel data);
    MyViewModel Read(MyViewModelId id);
    void Update(MyViewModel data);
    void Delete(MyViewModelId id);
}

At this point it should be obvious where this is going, but let’s continue for the sake of completeness. The UI developer would then define a class, say MyDevelopmentRepository, that implements the IDataRepository interface. The developer could stub these interface members, or even have them interact with a basic data store (even as simple as the file system). This class can be instantiated in the controllers (or handlers, or whatever) with the appropriate method being called such that he can build the UI as if he is calling the actual end-point(s). He can then define further repository classes that implement the IDataRepository interface, that represent different test and error cases, and he can swap these repository classes in place of the MyDevelopmentRepository in code to develop for different cases and provide his unit tests.

Then, when the end-point(s) are finally finished and we’re ready to do integration, the UI developer defines one final repository class–say MyMidtierRepository–that implements IDataRepository, and additionally has private members that maps the view-model to the end-point models (and vice versa), as well as serializing and deserializing the identifier. The CRUD operators would then internally call their corresponding end-points and map the view-model to the end-point model(s). This new repository is then swapped in, and we’re done (well, we should do integration testing). In addition to allowing the developer build the UI prior to the end-points(s) being completed, and allowing unit test to be built, this approach also insulates the UI code from any changes to how the data is retrieved. If at some point the data comes from a different source, we simply swap in a new repository.

And that’s it. I think it’s that simple. Perhaps I’m missing something, and I put this out there for anyone to point out to me what that may be. Else I really do see no reason why a UI can’t be developed independent of the end-point(s).

Advertisements

Book Review: JavaScript Promises Essentials (PACKT Publishing)

With ECMAScript 6 on the horizon of becoming the JavaScript standard, JavaScript Promises Essentials (PACKT), by Rami Sarieddine, proves to be a timely release.  A relatively quick read, though technical and not always easy, at 90 pages–which includes the preface, appendix and index–this is more of a small booklet and may cause the a consumer to take pause if thinking of buying the hard-copy version at over $20 (the electronic version is going for $9.99).  (For disclosure purposes, PACKT gave me access to a free electronic version of this book in exchange for posting this review on Amazon and front-end-fu.com).  If you can get by the price, though, I found the content of the book to be generally quite good with a couple annoyances I’ll get into shortly.

My personal introduction to the promise pattern came a couple years ago when I started looking into Windows 8 app development with WinJS, which includes an intuitive implementation of promises that conforms to the Promises/A standard.  With my positive introduction to this pattern–which is much more intuitive manner of handling async responses by chaining promise objects and passing your callbacks into the promises then method, rather than nesting your callbacks–I then started looking into Deferreds in jQuery.  In all honesty, though, I find I rarely use them as I find the jQuery implementation to be not at all intuitive.  So it is with this background, I dove into Sarieddine’s work.

There is a lot to like in this book.  He does a good job explaining how the Promises/A+ pattern works, how it differs from the Promises/A standard, where it is in terms of standardization with ECMAScript 6 and current browser support, what some of the libraries are out these that will polyfill support in the interim, and how error handling is done.  Additionally, he steps us a through an implementation of a basic Promises/A+ compliant promises object model.  I often times found myself saying I wish it would explain such-and-such, and within a few pages it would.  One such instance was I wished he would show us how to convert a jQuery Deferred into a promise, and then he did so with the Q and Promise libraries (p. 26).

My quibbles with the content are small-ish.  The first is the limited discussion about jQuery Deferreds, which doesn’t go much beyond saying they don’t follow a standard and quickly demonstrating how to convert them to promises with existing libraries.  Given the prominence of jQuery out in the wild, it deserves a fuller discussion even if not compliant with how standards are panning out.  Speaking of prominence, there is an entire chapter devoted to promises in WinJS, which does seem a bit much given WinJS hasn’t exactly taken the JavaScript world by storm.  But hey, that’s where I first encountered them (though I’ve chosen a lot of losers in my life with my experiments).  And if you happen to use WinJS, well, here you go.

The book also tends not to use practical examples, but rather the examples tend to be functions that return messages of the alert(“Hello there”) variety.  One in-depth practical example, maybe creating a mash-up calling into an API would, perhaps, help drill home how useful promises are, rather than being left simply with theoretical promise.  This likely would make a better chapter than the chapter devoted to WinJS.

And, while I hate to be that proverbial guy, the editing job on the book needs some serious work.  Throughout it appears auto-capitalization is used on function names if they are the first word in a sentence.  With promises, where the methods have name like “then”, this can make for a confusing read as on first read you think it’s the word “Then,” when it’s actually the method “then.”

But having said that, there is a lot of useful content in here, and you will come out of this with a solid understanding of promises and the current state of them.  Worth the read, but debatable if it’s worth the price.

Amazon Rating: 4 out of 5 stars

Free Front-End Books and Courses

With the pace of change in our field, keeping up to date as a developer is always an ongoing challenge, especially given you likely have a job to do and also want to maintain some semblance of a personal life. Myself, I tend to do a lot of reading on the bus to and from work–to the point I won’t now work any place where the commute will involve driving–as well as working on personal projects or courses after the kids go to the bed in the evening. As such, I’m always on the look out for new reading material, especially regarding advanced JavaScript, CSS, and modern design patterns and methodologies. Following are a number of resources I’ve found that contain relevant and timely front-end material, are of high quality, and are free.

Books
Syncfusion is currently offering over 40 technical books of 100+/- pages each, in PDF and MOBI formats, via a “Succinctly” series, here: http://www.syncfusion.com/resources/techportal/ebooks. And don’t kid yourself, these are quality books. For example, the JavaScript Succinctly book is written by Cody Lindley, and contains much the same material you will find in his highly rated JavaScript Enlightenment book. Beyond the JavaScript book, other relevant topics include, jQuery, KnockoutJS, AngularJS, Bootstrap, and Node. I personally found the Knockout.JS Succinctly book quite useful, and if you combine that with Ivaylo Gerchev’s series on Knockout, then you will have a very solid foundation from which to work from. One word of warning: you are asked to provide some contact information in order to download the books, and you may receive a marketing call. There are no obligations, however.

Moving on… Marijn Haverbeke’s Eloquent JavaScript is one of the very best introductions to the language you can find. And very recently the second edition of this book has been made available for free! Find it here: http://eloquentjavascript.net/.

Courses
I have taken a number of paid online courses, some of them well done (such as the some of the courses you will find at ed2go) and some of them taught me a different lesson than I expected. Aquent Gymnasium offers free online courses, focused on UI/UX, that are as well done, or better, than any of the paid courses I’ve done: http://gymnasium.aquent.com/catalog/. The course on responsive web design goes into a lot of detail, and is extremely well done. They also have offerings on jQuery, Bootstrap’s grid layout, and Node.js, amongst others. If you do well in one of their courses, you may be encouraged to consider working for them. No obligations, of course.

And finally, while more Computer Science oriented than focused on front-end development, you can find a number of free university courses online, as well: https://www.coursera.org/courses?orderby=upcoming&cats=cs-programming. Amongst these you will find courses on Android programming and Python.

And that’s what I have in my list, thus far, for material that meets the following threshold: either a book or course related to front-end development, is of high quality, and is free. If you know of additional material out there that you believe meets these bars, please do share in the comments section.

Book Review: Three.js Essentials (PACKT Publishing)

Three.js Essentials (PACKT Publishing), by Jos Dirksen, proved to be one of the tougher reads I’ve done in a while. When I agreed to review it, I believe PACKT was aware I had no experience nor knowledge of either Three.js or WebGL, or 3-D modelling period. (As a disclaimer, I received a free copy of this book in exchange for this review). I tackled this book from the perspective of someone with years of web development experience, solid knowledge of JavaScript, but having nothing in my background related to WebGL. And that’s what my review will reflect.

In the book’s preface, in a section titled “Who this book is for”, it states:

This book is for developers who already know JavaScript and want to get acquainted [empasis added] with Three.js. … All you need to know is some basic JavaScript and HTML.

“Acquainted” is an interesting choice of words and can be interpreted in a number of ways, I suppose. If what was intended was you’ll come out of reading this book with a basic understanding of what Three.js is about and capable of, then I suppose this book succeeds at that. If it means that a user, such as myself, will come out of this feeling comfortable I could tackle my own projects with it, I’m much less certain that’s the case.

The book is highly dependent on supplementary code samples you can either download from the Packt website or retrieve from GitHub. The book uses this code by highlighting parts of it to explain how to build a number of projects that make up the individual chapters. Where I had issues was the book did not present how to entirely build the projects, making it essential for you to often look between the code examples and what was being described in the book. To learn Three.js from this book I think you’d have to be extremely driven and willing to do a lot of digging beyond what is presented in the book, diving into the code examples (and not necessarily with guidance from the book), and other resources such as the online documentation. At that point, though, you’re not really learning from the book.

The impression I do get from reading the book is if you have some background in Three.js, or similar library, then you may find the book useful and find some of the techniques explained here to provide some “Oh cool! There’s something neat I can do!” moments. But if you are like me, an experienced web developer with no WebGL knowledge, I recommend you look elsewhere.

Amazon Score: 2 out of 5 stars

Animated Drop Down Menu With CSS3 (and no JavaScript)

Some thing quick, simple and fun this time.   A drop down menu, built solely with HTML and CSS, that is functional back to IE7, and animated for browsers that support CSS3 transitions. See the end-product, here.  Let’s get going…

First, the HTML structure.


<menu id="mainmenu">
  <ul>
    <li>
      <a href="#">Main 1</a>
      <ul>
        <li><a href="#">Sub Menu 1-1</a></li>
        <li><a href="#">Sub Menu 1-2this a long one goes for a while</a></li>
        <li><a href="#">Sub Menu 1-3</a></li>
      </ul>
    </li>
    <li>
      <a href="#">Main 2</a>
      <ul>
        <li><a href="#">Sub Menu 2-1</a></li>
        <li><a href="#">Sub Menu 2-2</a></li>
        <li><a href="#">Sub Menu 2-3</a></li>
        <li><a href="#">Sub Menu 2-4</a></li>
        <li><a href="#">Sub Menu 2-5</a></li>
        <li><a href="#">Sub Menu 2-6</a></li>
        <li><a href="#">Sub Menu 2-7</a></li>
      </ul>
    </li>
    <li>
      <a href="#">Main 3 this one goes for a while and does not wrap</a>
      <ul>
        <li><a href="#">Sub Menu 3-1</a></li>
        <li><a href="#">Sub Menu 3-2</a></li>
        <li><a href="#">Sub Menu 3-3</a></li>
        <li><a href="#">Sub Menu 3-4</a></li>
      </ul>
    </li>
    <li>
      <a href="#">Main 4</a>
      <ul>
        <li><a href="#">Sub Menu 4-1</a></li>
        <li><a href="#">Sub Menu 4-2</a></li>
        <li><a href="#">Sub Menu 4-3</a></li>
        <li><a href="#">Sub Menu 4-4</a></li>
      </ul>
    </li>
  </ul>
</menu>

A menu tag to provide semantic context, with a top-level unordered list to provide structure for the top level of the menu, and nested unordered lists to provide structure for the drop-down (or sub) menus.

Now, let’s do the layout with some basic CSS.

menu ul {
  padding: 0;
  margin: 0;
  list-style-type: none;
}

#mainmenu {
  width: 55em;
}
#mainmenu > ul > li {
  float: left;
  width: 25%;
}

#mainmenu a {
  display: block;
  padding: 0.5em;
  background-color: black;
  text-decoration: none;
  color: white;
  font-family: arial;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

Here we eliminate the default margins and padding, and bullets, for the unordered lists that make up our menu.  Then we float the list items for the top level menu to the left.  We also set a width for the menu, and divide this width equally (25%) among the four sub-menus. At this point we should have the items lining up correctly, with top level items going from left to right, and their corresponding sub-menu items rendering beneath.

We’re also going to do our aesthetic styling on the hyperlinks, as this will allow for the link/visited/hover/active behavior to take up the entire space of the list items in he menu.  To do so, simply specify the hyperlink (“a”) elements to be display blocks, and set any padding/margin on them.  We also set the default background color, font face and text color here, as well as setting the text-overflow to ellipsis in case the text is longer than our width.

We can now hide the sub-menus and get ourselves into our default state simply by adding this CSS:


#mainmenu > ul > li > ul {
  height: 0;
  overflow: hidden;
}

We just set the height of our sub-menus (he nested unordered lists) to 0, and hide any overflow so it’s not visible.  (We could use “display:none” here and also have it function, but this won’t work in conjunction with the animated effect we will add shortly).

So, to get our menu functional so the corresponding sub-menu displays when you hover over a main menu item, it’s simply a matter of setting the height to it’s appropriate height:


#top > ul > li:hover > ul {
  height: auto;
}

#mainmenu > ul > li:hover a {
  background-color: dimgray;
}

#mainmenu ul li a:hover {
  background-color: gray;
}

We also set the background color to change to indicate the hover over menu item and sub-menu item states.  At this point we have a fully functional drop down menu that works on browsers back to IE7.  And with no JavaScript!

Finally, we can animate the “dropping down” of the menu with a simple CSS3 transition.  We are going to do this on the “max-height” property of the nested unordered lists by setting them to have a max-height in the hover state that is greater than any possible height for our sub-menus.  In the default/non-hover state it will have a max-height of 0.  And we’ll set a transition for the max-height property to create the animated effect:


#mainmenu > ul > li > ul {
  height: 0;
  overflow: hidden;
  max-height: 0; /*start state of animation/transition*/
  transition: max-height 0.5s ease-in;
}

#mainmenu > ul > li:hover > ul {
  height: auto;
  max-height: 10em; /*end state of animation/transition*/
}

So the question may come up as to why we didn’t simply apply the transition to the sub-menus’ height attribute.  The quick answer is it doesn’t work, at least not if we set the height to “auto”.  Even if it were to work, and you may be able to get it to work if you set the heights of the menu items to a specific value, it may still not provide the ideal behavior.  By animating to the same “max-height” for each sub-menu, you ensure they sub-menus move at the same speed regardless of height differences.

And why not remove height altogether since we’re relying on max-height for the animation? Just a matter of preference for how the menu works when you mouse off the main menu item.  If we remove height, then you also see the menu animating to a closed/hidden state, which to me looks awkward, especially when another sub-menu is animating open at the same time.  Try it, and you may see what I mean.

And that’s it, an animated drop down menu with no JavaScript.  What I haven’t done is test this on mobile devices, though for that we may want to restructure the menu with a media query.  A possible future addendum for this article.

Questions?  Thoughts?  Feedback?

A Brief Exercise in Profiling JavaScript

I recently had to track down a memory leak while reviewing a video course–a series of videos broken up into 8 sections consisting of 5 videos each–that demonstrated the development of a couple of games with HTML5 technologies.  This is a brief recap of how I approached uncovering the leak with the hope it can provide others with a hands-on exercise using Google Chrome’s profiling capabilities.

The course primarily involved JavaScript coding utilizing the EaselJS library to interface with the canvas element.  I had just completed the sixth in the series of videos provided at which point the code had placed the game into a loop.  That is, as soon as the hero in the game died, the game immediately started over again.  Letting the game loop through a few times I noticed the game started to get sluggish.  A natural assumption would be we have a memory leak.

Here is the code in exactly this state (view leak in browser and download archive of code).

Of course, thinking as any developer would, I figured it couldn’t be my fault.  The course must have instructed me to do something wrong and introduce the leak.  The course came with code representing where you should be after each video, so to test my assumption the course was at fault I ran the code the course provided, and it did not become sluggish.  So I was left pondering what I had done to get the game into this state.

At this point the code included 9 JavaScript files I had written consisting of about 400 lines of code.  There was also a dependency on the EaselJS library.  Naturally, I downloaded the latest and greatest version of EaselJS–0.7.1–while the course used an earlier version: 0.5.0.  Between the two versions some significant changes have been made to the library, and the minified file was 79 kb.  So this wasn’t going to be as simple as commenting out a few suspect lines here and there to narrow down the origin of the leak.

Enter the profiling tools in Google Chrome.  At this point you may want to open up my code in Google Chrome, open Chrome’s dev tools (F12 in Windows, Cmd+Opt+I on Mac), and click on the “Profiles” tab.  Make sure “Record Heap Allocations” is selected, and click “Start.”  This will give us an object allocation graph on a timeline (in gray) as well as indicating the time of events (in blue).  Do this for a while and then stop the profiling by clicking the red circle.

There are a few events that you will notice occur naturally.  Our hero, who at this stage in development is a green rectangle, can collide with a yellow rectangle (a “coin”) and collect it.  Our hero can also trigger a game restart in a couple of ways: by colliding with a red rectangle (an obstacle), or by falling off a black rectangle (a platform).  You can also trigger an event as a player by clicking on the canvas, which causes the hero to jump.

So back to our initial profiling.  Looking at the time line we took, you will notice the object allocation increasing over time in a saw tooth pattern, which confirms we have a leak.  You will also notice that at each jump in object allocation we have a blue line indicating an event occurred.  If you watched the game play in parallel with watching the timeline being recorded, you should have noticed that this jump in object allocation occurred immediately after our hero died, either by colliding with an object or falling off a platform.

 

Heap Timeline - notice sawtooth pattern with increasing object allocation being triggered by events (our hero dying)

Heap Timeline – notice sawtooth pattern with increasing object allocation being triggered by events (our hero dying)

So we’ve now confirmed we have a leak, as well as identified the event that is feeding the leak.  The next step is to identify the objects that are being created by the event.

Back to the “Profiles” tab in the dev tools.  But instead of selecting “Record Heap Allocations,” we instead are going to select “Take Heap Snapshot.”  The plan is we’re going to take a snapshot of the objects on the heap before the event occurs, and then a second snapshot after the event occurs.  We’ll then examine the difference between the two snapshots to see if we can identify any specific types of objects that increase in number.

So after starting your game, click the button to take a snapshot (it’s OK if you don’t take it before the first death of our hero, he will die plenty of times).  Now wait until our hero dies one or two or more times, and then take another snapshot by clicking the gray disc above the listing containing the first snapshot.  You should now have “Snapshot 1” and “Snapshot 2” listed.  Then from the “Summary” dropdown, select “Comparison” (see screenshot, immediately below).

After taking snapshots before and after the event, select "Comparison" from the dropdown.

After taking snapshots before and after the event, select “Comparison” from the dropdown.

To provide some context for what we’re about to see, here’s a little background on how some of the code is structured.  The game is made up of “GameObjects” whose constructor function’s prototype object is an instance of an EaselJS Container (createjs.Container).  If you look at the code for this, you will also notice that GameObject.prototype.initialize calls p.Container_initialize (which is a reference to the initialize method initially created when the prototype object was instantiated).

Derived from GameObject, using the same same prototypal inheritance pattern, are Coin, Obstacle, Platform, and MoveableGameObject.  Hero is then derived from MoveableGameObject.  When a new game is initialized, a single hero is instantiated, as are 10 Platforms.  Upon the first Platform a Coin in instantiated, and for the last 9 Platforms either a Coin or Obstacle is instantiated (via a 50% decision made via Math.random). These objects are all added to the game’s “camera” property as children, where the “camera” is an instance of an createjs.Container.  This camera is a child of the stage, which is the createjs wrapper object around the canvas the game is played on.

As mentioned earlier, the game ends and restarts (loops) when the hero either runs into an obstacle, or falls off a platform.

So, with this background, you should notice something quite interesting by looking at the comparison of the two snapshots taken with the profiler (see image, below).

Look at the Constructors list to see if we see any object numbers building up.  See anything interesting?

Look at the Constructors list to see if we see any object numbers building up. See anything interesting?

Between my snapshots, the hero died three times.  Given this, and what you know of the object model for this game, three items should stand out in the constructor list.

For starters, we see 30 new Platforms were created, and 0 deleted.  As mentioned above, with each game restart 10 Platforms are created, and with 3 restarts, we see the Platforms being created, but we’re not seeing the old ones being GC’d.  And we also see 16 Coins and 14 Obstacles created, but none are cleaned up.  So we now know when the game ends, we’re either not deleting the old objects, or more likely we’re maintaining a reference to them that is preventing them from being cleaned up by the garbage collector.

So the next step I would take is examining the code that is called after our hero dies, which presumably cleans up the game objects before starting over again.  Looking in rush-game.js, and specifically RushGame.prototype.resetGame, we see the call that should clean up these objects (ie, this.camera.removeAllChildren):


var p = RushGame.prototype;

p.resetGame = function() {
  this.camera.removeAllChildren();
  this.camera.x = 0;

  createjs.Ticker.removeAllEventListeners();
  createjs.Ticker.addEventListener('tick', (function() { this.tick(); }).bind(this));
};

And if we look at RushGame.prototype.initGame, we see that Platforms, Coins and Obstacles are added as children to the camera, so presumably we’re doing everything right.  So what’s going on with this.camera.removeAllChildren?

If you use the debugger and place a break point at the call of removeAllChildren, and then upon hitting it, examine what this method is in the console, you will see this:

leak-removeAllChildren

So we see it pops each child (Platform or Coin or Obstacle) off the camera’s children array, and then set’s the child’s parent property to null.  Presumably the parent is the camera, and these objects should be free to be cleaned up by the garbage collector.  So… More digging…  Let’s start with the Platform constructor function in rush-platform.js.


rush.Platform = (function() {
  function Platform(width) {
    this.initialize(width);
  }

  var p = Platform.prototype = new rush.GameObject();

  p.category = 'platform';

  p.GameObject_initialize = p.initialize;

  p.initialize = function(width) {
    this.width = width || 120;
    this.height = 12;

    var shape = rush.CommonShapes.rectangle({
      width: this.width,
      height: this.height
    });

    this.addChild(shape);
  };

  return Platform;
}());

We see it’s prototype object is an instance of a GameObject, and the constructor function itself calls initilialize, which is defined on the prototype object and adds a shape via a call to addChild, which it presumably accesses via the prototype chain.  But more interesting is what is happening just above the definition of initialize, we see GameObject_initialize being set to the prototype object’s initialize method, and then nothing further is done with it.

Now if you were to surmise at this point that GameObject_initialize should be called in initialize, and tried this and then repeated the profiling exercise, you will find you have discovered the issue in code causing the leak, as you would be seeing the Platform objects now being deleted in your snapshot diff.  And if you look at the code in rush-coin.js, and rush-obstacle.js, you would see the same mistake, which I introduced through copying and pasting the Platform code.  So at this point you could simply fix your code by calling GameObject_initialize in all three initialize definitions, and the leak is taken care of.

But for the sake of academic completeness, let’s dig into the code a little deeper and understand why this caused a leak.  Back to Platform, we know it’s prototype object is a GameObject, and we know we don’t call the GameObject’s initialize method.  So what do we see in rush-gameobject.js?


rush.GameObject = (function() {
  function GameObject() {
    this.initialize();
  }

  var p = GameObject.prototype = new createjs.Container();

  p.category = 'object';

  p.width = 0;
  p.height = 0;

  p.Container_initialize = p.initialize;

  p.initialize = function() {
    this.Container_initialize();
  }

  p.hitPoint = function(point) {
    if (point.x >= 0 && point.x <= this.width &&
        point.y >= 0 && point.y <= this.height) {
      return true;
    }
    return false;
  };
  return GameObject;
}());

So we see that GameObject’s prototype object is an instance of a createjs.Container, and that GameObject’s initialize method does call the Container’s initialize method.  But since the GameObject’s initialize method is not being called when the Platforms are being initialized, then the Container’s initialize method is not being called, either.  We can also note that addChild is not defined in GameObject, so the addChild being called in Platform.prototype.initialize is coming from further up the prototype chain.  And if we go up the prototype chain we also find addChild defined on createjs.Container.prototype.

Even though I only have the minified version of the EaselJS library, it is still apparent what is going on if we look a the code for the two attributes off the Container’s prototype object.

createjs.Container.prototype.initialize


function (){this.DisplayObject_initialize(),this.children=[]}

createjs.Container.prototype.addChild


function (a){
  if(null==a)return a;
  var b=arguments.length;
  if(b>1){for(var c=0;b>c;c++)this.addChild(arguments[c]);return arguments[b-1]}
  return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.push(a),a
}

createjs.Container.prototype.initialize creates an array–children–in the this scope. However, remember that Platform (and Coin and Obstacle) don’t call GameObject.prototype.initialize, which is what calls this, so we don’t have a children array created on these objects. But all of the constructor functions for Platform, Coin and Obstacle have an instance of GameObject defined as their prototype object. So when we see this.children being referenced by addChild, it is Platform.prototype.children having an element being pushed on it (or Coin.prototype.children, or Obstacle.prototype.children), and since the constructor functions Platform, Coin and Obstacle never go out of scope, the elements of the children array off their prortype objects’ never go out of scope and don’t get GC’d.  And since these children elements reference the instances of Platform|Coin|Obstacle as their parent (this.parent, see addChild), those objects don’t get GC’d even though they are no longer elements in the camera.children array.

I realize there’s a lot in that last paragraph, and you may have to go back to the code (in the debugger, no less) to fit all the pieces together, but there you have it: the origin of the memory leak.  It even becomes more apparent if you do this: instead of calling this this.GameObject_initialize in the initialize method of the prototype object for Platfor|Coin|Obstacle, instead simply add the line “this.children = [];” in each initialize method, and the run and profile the code.  You will see the memory leak is gone.

All questions, comments and expressions of confusion welcome.