Just wanted to take note of how I did this, in case it helps anyone, or if I forget :)
HomeBrew
First I installed Homebrew, as I’m kind of sick of MacPorts and Fink (specifically how slow and out of date they tend to be). This was a matter of clicking on the ‘install homebrew today’ button, which linked me to their github page… where I found the following instructions.
So as it turns out this did not work, and instead I got an error message about ca certs. Fortunately it did mention that I should add the -k option to turn to turn off strict cert checking. so I did this instead:
So I went over to the MongoDB site and specifically their Quickstart OS X page. Since I have homebrew now I did,
brew update
brew install mongodb
note that I did not need to use ‘sudo’ before either of these commands, which is nice. After installing, it instucted me to issue the following commands:
Which I dutifully did. Note that the ‘launchctl load …’ command actually starts the ‘mongod’ database daemon, so there’s no need to start it manually. Simply typing ‘mongo’ starts the mongodb shell
>: mongo
MongoDB shell version: 2.0.0
connecting to: test
Note that >: is my prompt, in case you’ve seen Lost you may get the joke :) Now I can create a ‘collection’ by saving an item to one, like so:
> db.foo.save({a:1})
And I can query all the items of ‘foo’ like so:
> db.foo.find()
{ "_id" : ObjectId("4e6ffd8928d02c8f55a09dbb"), "a" : 1 }
I’ve just got started with MongoDB, but I have to say it looks like it will be really nice to work with on personal projects. No more fussing around with database schemas! Yay!
I just found out that the videos from both the JSConf 2011 and NodeConf conferences held earlier this year, are available online.
First off, the conference has an Oregon Trail theme, which I did not understand until I saw this video by author Sloane Crosley, which explains the game’s appeal delightfully. (Skip to about the 2 minute mark for the actual reading)
A really good explanation of the new Binary APIs for Javascript. Nice to see the author of the great Rhino book in person (at least virtually.) Kind of amusing to hear all the talk of BLOBs (Binary Large OBjects). This opens up a number of interesting possibilities, such as getting access to files from the user’s filesystem (with their permission, after they have selected it) without uploading them. Also image processing, and even audio processing and generation. However, browser support is still incomplete… Let’s hope IE supports these APIs in it’s next version.
This is a call to action to ensure that Javascript evolves properly, to prevent some of the quagmires we currently experience as developers. In a nutshell, we need to agree on common standards and protocols to prevent duplication of effort. Some of this work is underway, eg CommonJS, promisesA. Also some interesting facts about the history of the automobile and the road system which we take for granted.
A look behind the scenes of the Traceur Javascript compiler, which lets you write futuristic Harmony flavored Javascript, and generates present-day Javascript. This reminds me a bit of CoffeeScript, though here you’re still writing Javascript, albeit a version which does not yet exist. The suggestion is that you can invent your own Javascript.next features and hack the compiler to support them. If you’re interested in writing a compiler in Javascript, this would be a good place to start.
‘Freestyle RPC for Node’ (James Halliday)
An entertaining presentation on James’s dnode node module which allows seamless remoting between client and server code. perhaps not the most elucidating presentation (there is about 10min of random rapping towards the end) but DNode does indeed look awesome.
It seems like every single session from these conferences is available here. The only confusing thing is that the videos do not always have the same titles as the sessions at the conferences, so you may need to cross-reference with the jsconf programme
Jasmine is described on its site as a ‘behaviour driven development framework for testing your JavaScript code.’ I thought I would give it a try, using it while developing a new game with my Canvasteroids framework.
First off, though, I should address the different terminology here: what is ‘behaviour driven development’ anyways? Why isn’t it called a Unit Testing framework? To understand why, you should read this article The idea that the names matter really rings true for me and it always seemed weird to me to try and test something which does not yet exist. Thinking of ‘specifications’ rather than ‘tests’ makes a lot more sense to me. Also, thinking about testing ‘units’ of code is more likely to make your tests closely coupled to your implementation, leading to maintenance headaches and unnecessary, verbose tests.
Installing Jasmine is ridiculously easy: I just downloaded the standalone project, and extracted it as the ‘specs’ folder in the Canvasteroids project. Inside it is a SpecRunner.html file.. opening up this in a browser will run the dummy tests which are there by way of example. Then I removed them so that I could run my own specs. I also installed some Jasmine Snippets for Vim to make writing specs even easier.
I created a new spec file called BreakoutSpec.js in the specs/ folder and added the following:
12345678910111213
describe("Breakout Game Specs",function(){vargame;beforeEach(function(){game=newbreakout.Breakout();});it("should exist",function(){expect(game).toBeDefined();});});
The describe() function defines a Suite of Specs. The function given to it as its second argument contains the specs themselves. Each spec is defined by an it() function call, which similarly takes a function as its second argument. The first argument to both describe() and it() is a descriptive string which will be shown in reports. Within the it() function there are calls to expect() which will check specific things to determine whether the Spec has been fulfilled. See the list of them here. In this case we are simply checking that the Breakout game instance was created successfully. Obviously, beforeEach() is run before each spec. We need to include the spec in the SpecRunner.html file, which now looks like this:
123456789101112131415161718192021
<!DOCTYPE html><html><head><title>Jasmine Test Runner</title><linkrel="stylesheet"type="text/css"href="lib/jasmine-1.0.2/jasmine.css"><script type="text/javascript"src="lib/jasmine-1.0.2/jasmine.js"></script><script type="text/javascript"src="lib/jasmine-1.0.2/jasmine-html.js"></script><!-- include spec files here... --><script type="text/javascript"src="spec/BreakoutSpec.js"></script></head><body><script type="text/javascript">jasmine.getEnv().addReporter(newjasmine.TrivialReporter());jasmine.getEnv().execute();</script></body></html>
Refreshing the SpecRunner.html file, we see that this Spec fails. There are two failures, one which is the result of a run-time error while executing the spec (because the namespace ‘breakout’ in ‘breakout.Breakout’ is undefined, and because the expectation was not met (because ‘game’ was not defined).
So, I made a new folder called ‘breakout’ in the games folder, and copied the index.html file from Asteroids into it, renaming the reference to the Asteroids game class to be Breakout. I also created the new game class in a file alongside the index.html file, called Breakout.js, with the following Ext 4 class definition in it:
So we have a Breakout class now, but how do we load it in our test runner? Why not use the Ext JS 4 Class loader, just as we do in the game itself? This is what the updated SpecRunner looks like (we also need to load the ext-foundation.js file).
<!DOCTYPE html><html><head><title>Jasmine Test Runner</title><linkrel="stylesheet"type="text/css"href="lib/jasmine-1.0.2/jasmine.css"><script type="text/javascript"src="lib/jasmine-1.0.2/jasmine.js"></script><script type="text/javascript"src="lib/jasmine-1.0.2/jasmine-html.js"></script><!-- include Ext JS 4 Class framework --><script src="../lib/extjs/ext-foundation.js"type="text/javascript"charset="utf-8"></script><!-- include spec files here... --><script type="text/javascript"src="spec/BreakoutSpec.js"></script></head><body><script type="text/javascript">Ext.Loader.setConfig({paths:{'breakout':'../games/breakout'},enabled:true});Ext.require('breakout.Breakout');Ext.onReady(function(){jasmine.getEnv().addReporter(newjasmine.TrivialReporter());jasmine.getEnv().execute();});</script></body></html>
Note that we made the call to Ext.Loader.setConfig(), defining the required namespace ‘breakout’ to be the relative path of the directory containing the class file. And we wrapped the Jasmine code in a call to Ext.onReady(), which will only execute when the classes required have been loaded. This is handy, because we will not have to worry about adding them to the SpecRunner, which can be a chore with other Javascript Testing frameworks I’ve used. We will however need to update the paths of the namespaces used by any classes in the application, so that any namespaces are correctly resolved. And when we run the SpecRunner again … we get the green light! The spec succeeded.
So I admit this is a trivial spec… but it should be enough to get you started with Jasmine and Ext JS4.
I’ve been working with Ext JS a lot at work over the last year, and have grown to like it. Last year I went to the Sencha Conference in San Francisco, and was very impressed by the features of the upcoming release of Ext JS 4. One of the big changes is the new Class system, which makes defining classes easy and also loads required classes dynamically when required. The build tools which Sencha (The company which makes Ext JS) provides make it easy to produce a single compressed .js file of your app for deployment. All in all it is a great framework.
Ext JS 4 is well modularized, and you can use as little or as much of it as you like. For the Canvasteroids game framework that I’m working on, I decided to use the ‘ext-foundation.js’ file which is the essential core of the library, which defines the Class management system, as well as a useful collection of utility methods for the core Javascript types. However no changes are made to the native object prototypes, so there will not be complications when combining Ext 4 with other frameworks.
The Ext JS 4 class system lets you define a class as follows:
Obviously, the ‘constructor’ function is what becomes the class constructor. The ‘extend’ property will cause this class to inherit the given class. Note also the use of namespaces, eg ‘foo.Bar’ in the names of classes. In Ext JS 3 you had to explicitly declare all your namespaces, but in v4 this is handled automagically.
Mix it up with Mixins
Additionally, you can have ‘mixins’ which add in methods (or properties) of the given class. This is very helpful as it enables another way of re-using code besides inheritance. This is how you declare mixins (an example from Canvasteroids):
1234567891011121314151617
Ext.define('drawable.DrawableLine',{extend:'geometry.Line',mixins:['drawable.Drawable'],constructor:function(props){this.callParent([props]);//this is a base drawable class -- set context (required property)this.initDrawable(this.context);},draw:function(ctx){this.beforeDraw(ctx);this.ctx.beginPath();this.ctx.moveTo(this.start.x,this.start.y);this.ctx.lineTo(this.end.x,this.end.y);this.ctx.stroke();this.afterDraw(ctx);}});
The initDrawable(), beforeDraw(), draw(), and afterDraw() methods all come from the Drawable mixin class (which is defined in the same was a regular class except it does not have a constructor). Drawing is a behaviour, and this is a good use case for using a Mixin. As with inheritance, you can override methods or properties from a Mixin class. In this case I overrode the ‘draw’ method with a custom implementation. In this way Mixins can act like Abstract Classes, but you are free to use more than one at a time.
callParent() is super!
Also note the call to callParent() : this is equivalent to super() in ActionScript.. it calls the same method from which it is called on the parent class. So in a constructor it will call the super-class’s constructor. Note that the arguments must be passed as an array.
Getting Loaded with Ext.Loader
If you’ve worked on a large scale Javascript application, you know it can become a pain to maintain a large number of script tags, and resolve dependencies. Every time you add a new class to the system, you have to add it to the list of scripts includes in your HTML page, and you have to figure out where in the list of includes it has to go in order to have all of its dependencies satisfied and to satisfy its dependents. This is usually done by trial and error and can be quite annoying. Ext.Loader to the rescue! Once properly configured, you will never need to add another script tag again! Here’s how to set up dynamic loading in your main HTML file:
The ‘enabled:true’ attribute of the object passed to Ext.Loader.setConfig() is what turns on the dynamic loading of classes. When this is turned on, Ext JS will dynamically add a ‘script’ tag when it notices that it needs to load a class. By default, it will look for a file with the same name as the class (replacing ‘.’ with ‘/’) relative to the HTML file. If you wish to use a different path you will need to add a mapping to the ‘paths’ hash object. By default, the ‘Ext’ namespace is mapped to the ‘src’ directory of the library so it will load other classes from the framework if you are using them.
Then you load your main app using a call to Ext.require(). In this case I required the main Asteroids game class, which was in the same directory as the HTML file this code is in. The ‘Asteroids’ class itself has multiple dependent classes, and the Loader will recursively parse them until they are all satisfied.For example the ‘canvasutils.Context2D’ class will be resolved to ‘../../lib/canvasutils/Context2D.js’. NB: make sure you name your class correctly, or errors will occur in the loading process. In addition to any classes referenced in an ‘extends’ or ‘mixins’ definition, there is a ‘requires’ property which can be used to explicitly declare a class’s dependencies. For example in the Asteroids class, I have defined the requires as follows:
When the Loader is enabled, Ext JS will wait until all the dependent classes have been loaded before executing Ext.onReady(). At this point you can simply instantiate the class normally with ‘new’ as I have done. Alternatively, you can use Ext.create() with the class name as a string. This has the advantage that if for some reason the class was not loaded, the Loader will load the class synchronously. However, this is non-optimal for performance, and you will be warned in the console about this. Since I want to avoid this, and for ease of debugging, I tend to use the old fashioned form of instantiation with ‘new Xxx()’, and remember to add the class to the list of ‘requires’.
Note that the order of the classes in the ‘requires’ array does not matter.
Building a Deployment version
While loading .js files dynamically is nice for debugging, it is not optimal for deployment, due to all the additional HTTP requests. It is recommended to combine all the required Javascript files into one, and compress it by removing comments, whitespace, etc. If you have used the Ext.Loader as I describe above, this will be very easy. First you will need to install the free Sencha tools from here (see the links for the different platforms tools near the bottom of the page). Then use a terminal to go to the same directory as you HTML file and type the following command:
1
senchacreatejsb-aindex.html-papp.jsb3
This will create a .jsb3 (JSBuilder, Sencha’s JavaScript compression tool) configuration file for the application. If that worked then do this:
1
senchabuild-papp.jsb3-d.
And you should have a app-all.js file which will be the combined and compressed version of your app. You should create another HTML file for deployment which references this file, rather than the Ext.Loader config we used for develpoment. That’s it! Your Ext JS 4 app is ready to go.
This is a brief overview of the Class system, for more info see the excellent docs:
I was pleasantly shocked the other day to see a pull request in my GitHub account for the Canvasteroids game framework I recently created. There were the following features added to the Asteroids game:
score
lives
game over after 3 lives lost
an animation when the rocket is being thrusted
enhancements to the firing of bullets
a new Text class for the framework (used to display the lives and score)
Some kind folks from the Chico State Open Source Team had picked my project to flex their programming skills. I was quite impressed with the quality of their contributions, and that they were able to dive into the project which I admit is not really documented at all.
This has inspired me to continue my efforts on Canvasteroids, as well as documenting it better, to enable further collaboration. I’ve since posted on my blog about one of the patterns I use in the framework: ‘State and Transition Oriented Programming’. I’ve also started on a second game, which I will hopefully be launching soon.