Extending CreateJS Classes

      No Comments on Extending CreateJS Classes

CreateJS is a powerful library which tries to mimetic the behavior of flash/actionscript3 class hierarchy. It does a really good job, but some of the classes are left away. Maybe because they were too much flash dependent or maybe they were not used so much. There is one class I found quite useful which is not there anymore: SimpleButton. So I started to take a look to see how inheritance works in createjs and to be able to extend createjs classes.

If you took a look on the previous post, to see how to create classes in CreateJS style, you are already know almost everything. However, a few things can be done differently, because createjs proposes a slightly different mechanism to call functions defined in the superclass and provides some utility functions to be used in the process.

When we override a method defined in the parent class we need to invoke it before invoking the new version. For example let’s say we have a class PineTree and a method draw, which draws the tree. Then we extend the class creating a new class ChristmasTree. This new class override the draw method, to draw the decorations, but before drawing the decorations it needs to invoke draw method of the parent.

The solution createjs adopted was to provide a function which adds the superclass prototyp methods, under a changed name, in the subclass. If we would have PineTree and ChristmasTree classes, the draw method of the ChristmasTree would look like that:

In our previous post we extended the code by simply copying the prototype of the super class:

CreateJS provides a method to do that for us. The method is called extend; if you want to take a look at the source code you will see it’s not fancy at all and it does pretty much the same thing.  When we create a new class instead of directly copying the prototype its better to use the extend method createjs provides:

Then we can add out methods on the prototype( for example the draw method of the ChristmasTree ). However, at this stage our class does not have a mechanism to invoke overridden methods of the super class, like the draw method of the PineTree.

At this stage we need to use the promote function. You can take a look at the sourcecode to see it clones the method of the super class in the sub class with prefixed names. The method draw(ctx) of the PineTree will be available as Pine_draw(ctx) in the Christmas tree.

 

Here is the code to extend the createjs.Container and to create a Button class. The example is from the official tutorial for createjs inheritance:

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *