Blog Posts

Game development with JavaScript

Recently, we had a hackday at Liip, where we dived into game development with JavaScript. Our goal was to see how hard it is to produce a simple cross platform game using just JavaScript and HTML5 elements. Since we didn't want to reinvent the wheel, we decided to use a JavaScript game framework.

To make it short: we were very impressed at the state of the different frameworks around. We were able to put together a simple game in a suprisingly short time. Check it out here! (Thx to Chrigu for letting us use the graphics of his awesome iPhone game Herbert, the misanthropical fly).

Technical details

We developed our game using ImpactJS, a high-level JavaScript game framework that did a lot of work for us. While we briefly looked at some alternatives like Crafty and LimeJS, we didn't want to spend our time comparing libraries but get our hands dirty. We went with ImpactJS simply because Chrigu had already looked into it a bit, and because of their awesome demo game. The downside of ImpactJS is the fact that it's proprietary, though it's well worth the price of 99$.

In ImpactJS, one generally has three different types of objects: screens, levels and entities. Screens control the different game states. For example you could have a settings screen, a highscore screen and an actual playing screen. Because your game (unlike our demo) probably has different levels, there are simple JSON files that describe how a level looks and can be automatically loaded by ImpactJS. Background images, collision maps and entities are placed in there. Finally, entities are all interacive objects: The hero, enemies, coins, bombs and so on. Entities are distributed over the level, they are animated and interact with other entities.

In our case we put together a startscreen, the main screen with a level map behind it and an endscreen that appears when one accomplished the level. Within the game we have our hero entity, whose goal it is to navigate through the map without hitting enemies or walls. He also wants to pick up coins. Coins are entities as well and can be picked up by the hero increasing his health a little. When the hero hits a wall or an enemy, he loses health. Of course, these actions are accompanied by sounds. The hero, enemies and coins are animated, which is achieved by simply looping through different frames in a sprite sheet.

Our Experiences

- ImpactJS does a lot of work for you. It handles animations, collision detection, scene management, controls and scrolling of the screen

- ImpactJS is documented very well, and there seems to be an active discussion forum on their website

- The level editor bundled with ImpactJS ("Weltmeister") makes it very easy to set up level layouts fast. That said, the user interface isn't always intuitive (right-click to drag around the map, press space to insert something) and the level editor sometimes feels buggy

- We had quite some issues with the playback of sound, since there are still several tricks needed to have sound working in a wide range of browsers. We did not get the built in sound manager of ImpactJS running properly. We instead used SoundManager2 but we still had to do a hack to get it to work on iOS devices. The problem is, that iOS won't start the download of media until there is a user-input event, so we just required the user to touch the screen, before the game can be started

- Porting to mobile phones or tablets can be achieved by simply wrapping the game in Phonegap, but we weren't sure how to deal with different screen / viewport sizes and resolutions without making the game look distorted or blurry

- Performance was surprisingly good, even on mobile phones. That said, on an iPhone 3G, we only reached 30 FPS, which is the "lagging limit". So a game that has more elements would probably need performance optimisations in addition to ImpactJS

- We played around a bit with different ways to navigate, including using the accelerometer or touch gestures, but didn't get much support from ImpactJS in that regard

Overall we are very happy with the outcome and we are impressed, how fast a simple game could be put together. Have a look at the source code to see how straightforward it was. ImpactJS helps a lot in handling the interactive parts, allowing you to spend more time on the look and feel, which is one of the key factors for games. We're all looking forward to using ImpactJS on a customer project, but also to playing around with free alternatives and seeing if they measure up to the high bar that ImpactJS has set!

Alain, Chrigu, Colin

Related Entries:
- Applying Niwea: TV Sélection iPad app
- Barcode reader Hackday
- Vanilla is a NIWEA
- Open Sourcing Radios - A PhoneGap iPhone/iPad app
- The technical details behind the Radios App

Comments [0]

Applying Niwea: TV Sélection iPad app

The Tages-Anzeiger TV-Sélection iPad app has been available for download in the Apple app store for about a week now.

Huh?

TV Sélection is an app that lets you watch TV shows on your iPad. The focus is on shows in four different categories, hand-picked by the arts and entertainment editorial staff of Tages-Anzeiger, one of Switzerland's biggest newspapers. At the same time you can watch any other show on a wide range of channels by using the search functionality, with just a few minutes delay from the time it airs on TV.

NIWEA!

From a technical point of view, the app was implemented completely using Javascript, HTML5, and CSS, and wrapped as an iPad application using Phonegap. While we didn't take advantage of Phonegap's big selling point of being able to deploy the same code to multiple device types, being able to use HTML/JS/CSS played to our strengths. The other advantage though, was that we were able to develop and test large parts of the app directly in the browser, without having to constantly rebuild the code and run it on the device or a simulator. And that right there is the concept of NIWEA - writing code that can be re-used with no or very few changes across multiple platforms.

Where NIWEA breaks

When you're running on a device you want to take advantage of that devices native functionality. That may be the camera, accelerometer, or contacts. In our case we had three use-cases: We wanted to show notifications when not in the app, we wanted to use the devices keychain to store login details a bit more safely, and we wanted to take advantage of the fact that millions of users have their credit card information saved in their iTunes store account. We were able to do this by using phonegap plugins, one for local notifications, another to access the keychain and a third to handle In-App purchases.

And that's where the NIWEA concept cracks a little. Since these plugins rely on Objective C code to interact with the system, that functionality won't work on other devices. In some cases there may be plugins for your other device as well, and you can drop them in with little or no changes. In other cases you may have to write your own plugin, or just not offer all the features on every device. Since, again, we were only building for the iPad we weren't impacted much. We wrote a quick mock to simulate the keychain using cookies so we could continue testing in the browser. The missing local notifications hardly impacted us, and In-App purchases ended up being easiest to test on the device itself.

Look ma, no server!

While Phonegap was new to everyone on our team, it wasn't the only interesting thing from a technical point of view. One of the limitations of the whole project was that everything should run on the app - there is no backend, there are no servers.

OK, that's not entirely true - we access the tv shows and playlists through a (non-public, sorry) Zattoo API. We didn't control this ourselves though, and so anything that needed server-side code had to be planned and coordinated with Zattoo's developers. Since this obviously generates some overhead, every feature was examined to see how it could be done without requiring a backend. Want to send an email with debug information? Instead of sending it from a server, use a mailto link to open the iPads Mail app with some prefilled content. Want to use Push notifications to let the user know when his license expires? Sorry, push notifications require a server, but we can use local notifications instead, we just lose some flexibility because we have to trigger them when the subscription starts. In-App Purchases? There's a bunch of back-and-forth between Apple's servers and a callback URL to verify receipts and such - in this case Zattoo ended up extending their API to handle Apple subscriptions, with us simply passing on the receipt data we receive when the purchase is made.

More fun stuff

Other interesting details: We used WebSQL to cache the shows locally and allow you to save shows in your favorites. Probably because the WebSQL spec isn't being developed further there isn't a lot of documentation on what SQL operations you can actually use with it, so that was a bit of trial and error. Also, having database calls be asynchronous just seems like unnecessary complication.

We used the HTML5 video tag to display the video stream of the show. In general this works fine, but one thing to note is that if you use the default iOS media player instead of building your own controls, you lose the possibility to catch javascript events on the player area. For example, we were able to catch the touchmove event everywhere on the page to prevent you from being able to scroll/drag the page up and down, but we weren't able to prevent dragging on the player interface.

Finally, we used YUI3 as a javascript framework, where the main thing worth highlighting is the ScrollView module, which handles the vertically sliding list of shows. This worked well, but as the scrollable area grew, we did start seeing performance problems. To resolve this we decided not to display shows older than 30 days, which made scrolling much less jumpy! The other awesome feature of YUI3 which we used, and missed while using jQuery in another project, is the possibility to set dependencies when loading a module. The module will then wait to be initiated until all the required modules are loaded.

Let me at it!

Go ahead! The app is available for free in the App Store, and you'll receive a seven day trial in which you can watch any show. Unfortunately, you'll only be able to watch the shows if you're within in Switzerland due to licensing restrictions.

Related Entries:
- YUI Training
- Backbone.js, a micro MVC for javascript
- Kinect Hackday
- Vanilla is a NIWEA
- The Tagi iPad App done in NIWEA aka html5/CSS

Comments [2]

Niwea Application Development - First experiences

Since quite a while now we're developing a NIWEA based app for one of our clients. If you don't know what NIWEA is you can read our earlier blogpost.

It was a very interesting new challenge. At first I thought cool, now I can use all the fancy HTML5 and CSS3 things I read so many articles about. Later I realized that creating a native-looking app with just web technologies is not all sunshine.

There are a few issues you may experience that are typical to webapps. These concern:

  • - Rotation & Calculation issues
  • - App Resume
  • - Offline availability
  • - Singlepage Problem

Rotation & Calculation

Whenever you rely on winHeight for your overlays, widgets, flyouts or lightboxes you will run into trouble. This caused by the constantly changing window height in iOS.
There are 4 possible states you need to be aware of:

  • - URL bar hidden
  • - URL bar out
  • - URL bar overlapping (during a request)
  • - Carrier bar overlapping in Add2Homescreen (standalone) Mode
All those situations may occur in landscape and portrait mode. Therefore there are 8 different heights & widths you need to be aware of and test your calculations with. Now you could just hardcode values for those 8 possibilities but that's not a good plan if you also want to support Android, WebOS and Win7 Phones.

A generaly good advice is to use :
 window.scrollTo(0, 1) 
before you're doing any calculations that rely on winHeight. This will hide the scrollbar and reduce the possibilities.
When you're in standalone mode you can just subtract 20px from your winHeight and add 20px padding to your content div.

 if (true === window.navigator.standalone) {

     winHeight -= 20;

     Y.one(#content).setStyle('marginTop', '20px');

 }

Rotation

All the places where you use calculated values need to be rotation aware. That means whenever the device rotates, you need to recalculate. This is best done by listening to the orientationchange event. Most devices also fire the resize event, but in my experience it didn't prove very reliable. Sometimes the phone is too busy and it doesn't fire any event at all. This bug has been resolved in iOS 5.

Singlepage

Whenever you're in standalone mode and click on a link, it will open in Safari. I'm not sure what Apple thought was the use of that but it's one of those problems you just need to fix.
To avoid this issue you can create a CSS class that is applied to all links that should not open in Safari. Add a delegate event handler that is listening to all click events on those elements.
Whenever a link is clicked, prevent the default behaviour with e.preventDefault(); then extract the URL and request the content through Ajax. That way Safari does not open.
Another workaround is to do POST's with hidden forms. This is helpful for logouts or other things you want emediate redirect and don't want to wait for the Ajax response to bounce back.

App Resume

We're used to multitasking and we expect apps to stay in the same state as they were when we left them. This works great if you use your NIWEA App inside Safari. In standalone mode it works different. Whenever you close or switch to another app, iOS forgets about the state of your app. Once you relaunch or switch back it will reload the entire app. Not on the last active url but on the url it was bookmarked too. The solution to that problem is simple. Whenever you request an url in your Singlepage code, put the last active url into localStorage. Once the app relaunches, check if a url is in localStorage before loading the starting page. This makes it necessary to have a so called loader Seed which is a construct that holds the navigation elements but loads the content after the initial load is done. The loader seed is also helpful if you want your app available offline.

Scrollviews

There are some nice libraries to make a scrollable div for mobile devices. You might ask yourself why not just do overflow: scroll. It does indeed work, but you will have to scroll it with 2 fingers. One of the most famous library is iScroll.

If you don't care for iOS 4 there's a very easy alternative called overflow scrolling:
 .scroll-x, .scroll-y { 

     -webkit-overflow-scrolling: touch; 

 }
This will allow you to have the element scrollable with 1 finger.

Offline availability

The concept how we solved the offline concept would enlarge this blogpost way to much. I already described what we did there on my blog. If you're interested check it out there.

Tools

Simulator

The obvious one is the iOS Simulator. It comes in very handy when you need to check your application on iOS 4 and 5. You can easily switch between versions and devices. Also you can reset the entire device. This is very useful if you want to clear the cache and the local database. The Simulator comes bundled with XCode. Once you've installed XCode, navigate to /Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app and put the App into your Dock.

iWebInspector

This tool allows you to inspect your html inside the Safari of your Simulator. You can change classes, edit markup and access the local databases. It's also possible to access the apps in standalone mode. Basicly you can do everything you can do in the Chrome Developer Toolbar.
iWebSimulator is available for free on http://www.iwebinspector.com/

Retrospective

All in all is it a nice challenge to develop NIWEA applications. It's nice to use new technologies and face problems that differ from the usual "it looks weird in IE" problems. But what you and your customer need to be aware of is that it's not going to be as fast as a native app out of the box and some things will need more time than in a native app. What you get in return are multi-platform capabilities with much less effort than the "traditional" native approach.


Comments [0]

Late recap JSConf.eu in Berlin

I waited with this blogpost until slides and videos became available. Now it seems that they all are here.

A collection of slides you can find here: 
https://gist.github.com/1256066

Also the videos are online. Check them out:
http://blip.tv/jsconfeu

Each talk on the ground floor was illustrated by Anna Lena Schiller. The results are awesome! And keep in mind that she often had no clue what the speaker was talking about:
Flickr Link

The Conference

Quite some folks of the javascript community came together in Berlin on the 1th and 2th of october 2011 for the third time. With over 200 people from all around the world and around 37 speakers to various topics. There were not only well known faces but also quite a few new ones and the different topics were spread wide. From traditional website usage over javascript game development to insane crazy stuff to things everyone can use/participate. JSConf.eu has something for everyone.

It was an amazing conference and we had a damn good time over there. The conference comprised two days of talks, each followed by a big party to meet and exchange with the others.

The Talks

And while I was enthused by all talks, I like to name my personal favorites.

This is not just about the content of the talks, it is also about how the speakers presented their talks and if they were able to fascinate the audience.

- Community JS reloaded
how to rock as a movement

- How to be an open-source gangster
How to succeed in open-source by embracing the ancient art of gangster rap... Keep it real!

- 140byt.es: Building a web framework, one tweet at a time
Very impressive ways of reducing the code in javascript snippets. Nothing you really want in a real project but very sexy to show off.

- Beyond JavaScript
A new way of looking at programming languages. Whether javascript or something else ;)

- Messing with JavaScript and the DOM to measure network performance characteristics
Interesting talk on how to measure network performance characteristics with javascript. Things like bandwidth, latency, TCP connect time, DNS time, IPv6 connectivity, port scanning.

Not just the conference

After the conference our team took two days of vacation, to use the chance to be in Germany’s capital city. We went to explore the city. These days were in no way computer related and I would recommend it to everyone. Its a very good team experience and you got some time to think about what you just listened to.

Thanks!

At this point I like to send a big “THANK YOU” to the folks of jsconf.eu, for organizing such an awesome event. But not just to the jsconf organisation team, also to everyone who joined and made it to such an awesome experience.

And last but not least. Many thanks to L//P for cheering up their developers to such things by providing them an education budget.

Keep it real!


Comments [0]

A frontend editor for Symfony2 CMF with the help of VIE

Yesterday we started working on an editor for the Symfony2 Content Management Editor, the LiipVieBundle. We use VIE and - until something non-GPL comes along - the Aloha editor. VIE is a piece of javascript on top of backbone.js that handles storing data with a REST backend. In Symfony2, this is a breeze thanks to the FOSRestBundle. Sounds complicated? Its actually quite simple, at least for the user. I made a short video to show how it looks.

You can try this out in the CMF Sandbox. Currently, its just a proof-of-concept implementation. For example, we make no authorization check whatsoever. In the upcoming weeks, we plan to do the following:

  • Only activate VIE if the user has the required role (inject an authorization service into the VieController)
  • Support authorization service in REST controller
  • Image insert feature in aloha
  • Find a way for developpers to configure what editor to use for each field
  • Support binary fields / file attachments
  • Autosave while editing to not lose data on connection errors

If you have feedback or inputs to this, please tell! And if you can contribute, you are more than welcome to do pull requests or comment on commits. Whatch the LiipVieBundle and the sandbox to see what is happening.

Related Entries:
- What Liip did after winning the IKS semantics UX contest
- Symfony CMF hackday october 22nd in Cologne
- Progress on PHPCR with a hackday
- Doctrine PHPCR-ODM now handles versioning
- Multilanguage support for Doctrine PHPCR-ODM

Comments [11]

YUI Training

We already hosted a well received and interesting YUI3 introduction training. You can read about it here.

We will host a training about the "YUI Building Blocks"  in a half day workshop on the 9th of June in Zurich. This workshop will take place twice once in the morning and once in the afternoon. They are open to the public, please get in touch with us if you want to join. Places are limited, first come first served.

Sometime in July we will host a full day of YUI3 training which will repeat the introduction and the building blocks workshops. This will only take place if enough people are interested so please leave a comment.

Related Entries:
- Applying Niwea: TV Sélection iPad app
- Backbone.js, a micro MVC for javascript
- Kinect Hackday
- webOS Hackday at Liip
- Techday Slides: PhoneGap

Comments [6]

Liip @ JSDay/PHPDay in Verona, Italy

Earlier this year one of my colleagues told me during the daily scrum that he plans to attend the PHP conference PHPDay in Verona, Italy. I thought that was an excellent idea and bought a ticket the same day. It turned out that at the same time and place also the JSDay would take place, the first Javascript conference in Italy ever. That was just perfect since so far I was always a little scared of writing Javascript because I had basically no experience in doing so. I'm not saying that I became a Javascript expert just by attending a JS conference, but I surely learned a lot :-).

So in the end we were three Liipers to set off for Verona and we were about to meet some more there (including two ex-Liipers). So Liip was quite well represented, which was also noticed by the organizers ;-).
The two conferences were hosted by the italian PHP user group and the guys did an awesome job. Hey, they even produced a PHPDay shirt for girls. According to them they are the first PHP conference doing so. So, *thumbs up*.
So, what did we actually learn during those four awesome days in Italy?

JSDay

The introduction talk "Even Faster Websites" was given by Steve Souders and he talked about how to improve the loading time of a website and also the users perception of that loading time. The sooner the user gets some feedback the faster the website is in his eyes. And to make sure users get feedback as soon as possible we should make sure that loading and execution of Javascript files do not block the loading of the rest of the website. More information can be found in the book of the same name by Steve Souders or parts of it were also presented by Pierre Spring in one of his techtalks.
Moreover I attended talks about the current state of HTML5 (slides), introductions to node.js (slides) and backbone.js, a very colorful introduction to two Javascript frameworks Cappuccino and SproutCore, two frameworks based on the idea of Mac's Cocoa framework, (colorful slides) and last but not least a talk about OOP in Javascript by Pierre Spring (slides).

PHPDay

Caching

For me PHPDay started with a workshop about caching by Fabien Potencier, starting off with the question about who in the room has already read the HTTP specification. We learned a lot about the different caching headers and what impact they have in what server setup. After the theory we played around with the different headers with a small silex app. Find more details about that workshop in the blog post by Patrick Zahnd.

RESTful web services

Another very interesting talk was given by David Zülke, chief developer of the Agavi framework, about how to define RESTful web services. With real world examples of badly designed APIs (e.g. the twitter API) and explaining how it could be done better he explained very well what is important when designing RESTful web services. Find more details about that talk in the blog post by Patrick Zahnd.

Profiling your PHP application

Lorenzo Alberton suggested in this talk some tools that can be used to profile your PHP application, mainly xhprof that was developed by facebook. He also explained how to interpret the results of such a profiler and where to start looking for possible problems. Some examples:
- if a website accesses the database, these calls should usually be at the top when sorting the profiler data by CPU usage
- when sorting the results by number of function calls find out if that function really needs to be called that often or is the call maybe in the wrong place, e.g. inside a loop where it could also be outside
He also gave some hints on how to optimize some things on system level, for example:
- if you don't use htaccess files turn it off in your server config, otherwise the server searches for those files needlessly
- always put a favicon.ico into your project so there is no error and the 404 error handler is not triggered in the case where you use a framework
Find more interesting optimizations here.
Oh, and by the way, don't use PHP error suppression. One reason is what PHP does when it encounters an @: it sets the error reporting level to 0, executes the function, formats the error messages and only then it actually checks the error reporting level. More reasons why you should not use it can be found here.
I've also seen a talk about how dependency injection works (slides) and from the same guy a talk about how to test untestable code, giving some ideas about how to mock certain services like mailing in non-tested legacy applications so they can be tested (slides).

Conclusion

The talks were very interesting, the venue was beautiful (go to Verona if you've never been there, best next year for the PHPDay 2012 ;-)) and people were awesome.
See you at PHPDay 2012!!!


Comments [1]

Liip @ linuxwochen.at

Earlier this year I was invited to speak at the Linuxwochen in Vienna first in May. The Linuxwochen is a conference taking place in different time slots at different cities in austria. Besides Vienna these are Graz, Linz, Krems, and Eisenstadt.

This years Vienna conference was hosted by the FH Technikum Wien, not only providing the accommodation and infrastructure for the conference, but also a very stable and reliable wireless network which is not too common on conferences.

What did I talk about?

PHPUnit

I was asked by the organizers to talk about PHPUnit. Preparing the talk I thought about bringing some lesser known features, assertions, and annotations to the audience attention. Starting with a selection of command line switches (like --filter, --group, --testdox) I pointed out that some switches only work in combination with previous set annotations and how to use them in a clever way.

This brought me directly to the annotations part. This section of my talk introduced the usage of annotations and highlighted a number of imho most useful annotations provided by PHPUnit. So do the @ticket or @group annotation relate a test directly to a ticket inside of an issue tracker if the value of the annotation is the identifier of the ticket provided by the issue tracker. Using the --group switch, only the tests registered in the requested group are run. This makes it very easy to verify if the bug had returned or not.

In the third section of my presentation I spend some time on some well overseen assertions of PHPUnit. Since I am a big fan of XML/XSLT and the Document Object Model in general, it was a pleasure to find out that PHPUnit has quite a number of assertions verifying the XML string or DOM-object returned by a method or service. Per example expecting two DOMNodes, assertEqualXmlStructure() is able to identify the differences between them and shows them in a diff-like report. By providing true as the third argument, this assertion will also take the attributes into account. This makes it very easy to spot changes or inconsistencies in the response.

Last, but not least I talked about different ways to test for expected exceptions. Therefore I showed some tipps and tricks using the mocking library of PHPunit.

JavaScript/jQuery

As usual on conferences some speakers get ill or cannot attend on short notice. This is were Jakob Westhoff and I were asked to talk about something JavaScriptish. After a short discussion with the audience we agreed on talking about some of the features of jQuery 1.6.

Having no slides we improvised using the provided black board and chalk in order to make things more clear to the audience. It turns out that this is definitely a way of presentation I should do more often ;)

In our presentation we spent most of the time explaining the concept of promises, futures, and defers. This fantastic concept to make asynchronous request ways work together is actually an old one, but was raised again by the commonJS group back in 2009.

This concept makes it very easy to manage asynchronous work paths of your script and, which is the best part, make race conditions disappear. It would be too long to tell you all about the concept right now, but for further reading the commonJS specification is a good place to start.

Will there be a next time?

Certainly. I had so much fun meeting and talking to really nice people and since the Linuxwochen are an annual event I think I will be back next year. Keep up good work fellows!

Related Entries:
- A workaround for the missing git submodule support in Bamboo 3.1
- Jackalope - JCR for PHP started
- webtuesday: Selenium
- Visual Code Coverage with SimpleTest

Comments [0]

Backbone.js, a micro MVC for javascript

Backbone.js is a small javascript MVC framework, developped and open-sourced by documentcloud.

context

We used backbone here at Liip for some small js projects (mobile and web), specially for a js game which was pretty easy UI wise but contained a lot of internal logic.

why MVC?

Usually the first question is 'do you really need MVC for javascript?', and i guess there is no real answer to this... The truth is that it helped us a lot in clarifying what to do and how to structure our application. As we all have a different background within the team (Php, Actionscript, Python) 'speaking MVC' was a kind of common language.
Anyway in most of js apps you'll need a router, and objects that act as models and views. Call it as you want... it still looks a lot like MVC :)

why Backbone?

As said before we wanted a way to structure the javascript part of our apps. The goal was to have a tiny MVC layer that we could easily reuse and that would ease our life without too much overhead. And that's exactly what Backbone is!
For us the main points of interest were that it provides:
* base components for both the views and models/collections
* a simple router (match url to function) with optional parameters
* an event mechanism for inter-components communication
* an easy way to update views on model modification
* scoping facilities (mostly through underscore.js which is the only pre-requisite for Backbone)
* template integration

how?

Templates

We used only 1 html file containing the base div structure and templates with placeholders. Backbone (via underscore.js) allows you to define templates like:
<script type="text/template" id="my-template">

    <div class="myclass-<%= id %>">

        <p><%= label %></p>

    </div>

</script>
You can then call the _template method with an Object as argument.. Nothing revolutionary, but quite helpful!

Structure

For the js part we first started with 1 js file containing everything (models, views, etc..) as presented in the official example on backbone web page. This turned out to be not so maintainable as the file grew bigger and bigger, so we refactored to use 1 file for each logical part. In our case we had 1 for the 'simulator' where computation were done, 1 for the router, 1 for the game logic, and several for the views. All those components were pseudo namespaced in an object that we called 'app'.
This led to a quite decoupled application with components that have a clear role and scope. Nice!

Events

Who says decoupled says communication, and here again Backbone helped us by providing an easy event system. For example, at first we had some concurrency problems on start up, so we decided to just trigger an event when all components are created. Something like:
// in main.js

// initialize all components here

this.trigger('ready');


// in any component

this.app.bind('ready', this.onReady);

onReady: function () {

    // do stuff

}
and with a little help of underscore.js we even can set the scope of 'onReady' function as the component:
_.bindAll(this, 'onReady');
pretty easy huh?!
It works the same for views which want to listen to model changes. By default models trigger some useful events like 'change' or 'error' (more on this afterwards) on value change. To set or get a value on/from a model you use:
this.model.get('key');

this.model.set({'key':'value', 'key2':'value'});
This has some added value: you can use the default model validator very easily:
// just override the validate function

validate: function(attrs) {

    // do custom validation based on passed attrs and return true if ok or any string ('not valid value')

}
Returning anything else then true will trigger an error event that you can catch in your view and handle as needed.

Router

The 'controller' part in Backbone is a simple router. It allows you to map methods to urls, again very easily.
routes: {

    'main': 'mainHandler',

    'product/:id': 'productHandler'

},

productHandler: function(id) {

    // this will be called when /product/21 is reached, with of course id=21

}
There are a lot of other features in Backbone that i could talk about... History management, sync with backend, all views methods, etc... but hey! time for stützbier :)
NB: you can also find backbone and underscore.js in the microjs list. Happy coding!

Related Entries:
- Applying Niwea: TV Sélection iPad app
- YUI Training
- Kinect Hackday
- webOS Hackday at Liip
- Techday Slides: PhoneGap

Comments [0]

Kinect Hackday

On Monday 11th of April we (Dan, David, Gerhard and me) connected Microsofts Kinect sensor to play around with the amazing 3D signal the gadget provides. The goal was to create a small image carousel, controlled by the sensor. We wanted to try two different approaches: one with Flash and the other one with JavaScript.

The Flash way

Accessing the 3D data with Flash was quite easy since I couldn't wait and already played around with the Kinect before. It also seems that there is already more stuff around for the Flash way (compared to the JavaScript way). We used OpenNI and as3kinect and the results after only few hours were very promising. You can control the carousel by moving your hand left and right. If you want to look at a pictureit in more detail, you can literally grab it and do so. You can then use the familiar multitouch gestures to zoom in and out. When you're finished with that, you can throw (again: literally) the image back into the carousel. Look at the video to get an idea of the demo app:

Some background info: With as3kinect you can access the skeleton and depth map data from OpenNI directly in Flash. You can then track 14 dots of the body in real time. What you don't get yet are gestures (exception: Touch gesture). So we had to do some custom math to recognize things like "swipe", "push", "pull" and so on. There is the middleware NITE which intends to detect these gestures, but it's gesture detection feature is not used in as3kinect (yet).

The JavaScript way

There is an amazing video demonstrating a browser plugin called DepthJs. But this was all we found that was done with open web techniques. So what we did: David and Dan built a page with HTML5 WebSockets and the jQuery HTML5 Carousel. The client simply connects to the server and listens for messages like "push", " swipeleft" and "swiperight".
For the server side, we wanted to use Processing and thus needed a Java binding of the Kinect signal. We found Processing Simple-OpenNI and added the "push" and "swipe" detectors. To install it, you first need the Kinect drivers, OpenNI and NITE. We were successful with the guide of SensorKinect.
To provide the data over WebSockets, we needed a WebSocket implementation for the Java side. On a first attempt, we found only bloated stuff that brought Tomcat or even JBoss into the game and would have make it pretty complicated to just open a socket connection. After wasting some time trying to "quickly" implement it ourselves (the handshake is really pretty freakish) we finally found the Java-WebSocket library which perfectly suited our needs.
The code we created is available on github.
Here is a shaky demo video:

Conclusion

The hackday was quite a success - we reached our goals and implemented both, a JavaScript and a Flash client. The Kinect sensor really is a great tool. Also it is amazing how many libraries allowing you to do your own stuff are available already. One big question is if this or similar devices will become available for mass market applications. Right now the Kinect is a great gaming interface and an interesting tool to make lab experiments. But what if computers/TVs had built in a 3D sensor out of the box like they have webcams now? The possibilities would be countless, but would we really want to do something like Google Motion? Let's see;) Anyway we are very curious what the Kinect future brings.

Edit: Asus will soon bring a NUI-device for PCs to market. Thx for the hint @sandro

Related Entries:
- Applying Niwea: TV Sélection iPad app
- YUI Training
- Backbone.js, a micro MVC for javascript
- webOS Hackday at Liip
- Techday Slides: Flash and the Quest for Accessibility

Comments [2]

Next1-10/48