krawaller http://blog.krawaller.se web & smartphone tinkering posterous.com Fri, 04 Nov 2011 03:45:00 -0700 CoffeeScript overview and resource inventory http://blog.krawaller.se/coffeescript-overview-and-resource-inventory http://blog.krawaller.se/coffeescript-overview-and-resource-inventory
An overview of CoffeeScript and good learning resources

As I've written about previously (although far from as much as I hoped to), I'm teaching a course at Linnaeus University on Advanced JavaScript for RIA creation. In the course, parallell to creating a RIA, the students are also tasked with doing a deepdive into a related subject of their own choosing (most often on a technology employed in the RIA creation).

Because I'm still working my way to a 3rd year degree myself, I ended up in the weird situation of getting to take my own course! Although not giving myself a grade, unfortunately. I made my deepdive in CoffeeScript, which I thought might also be fit for the Krawaller blog.

So here it is: a repost from my student alter ego, an overview of CoffeeScript:

 

What is CoffeeScript?

Briefly explained, CoffeeScript is a thin syntactical layer on top of JavaScript. You write CoffeeScript, it compiles to JavaScript, which is then run in the browser (or Node, or wherever) in the usual way.

As has been widely realised the last few years, JavaScript is a most excellent language when wielded right, utilizing its expressiveness and applying functional programming.

However, the syntax is far from as elegant as the underlying language. We all know the story of how Brendan Eich, JavaScript's creator, was forced to make it "look like Java". Had he not been wearing that shackle at the time (and not had the very short timespan to work with), JavaScript would have been looking very differently, and there likely would be no need for CoffeeScript.

But this, in essence, is the problem space that CoffeeScript tries to solve: it aims to negate the clunky syntax, exposing the beautiful language beneath. It does this by:

  • ...using significant whitespace. We're already indenting our code, so why should we also have to enclose a function body in curly braces? In CoffeeScript, we can declare objects and function, and use controlstructures such as if or switch, with just whitespace to signify the depth.
  • ...cleaning the syntax. By sacrificing the (unnecessary) ability to have many statements on a single line, we negate the need for semicolons completely. CoffeeScript also strives to be more readable, by changing existing keywords and operators to more succinct and self-explanatory versions. Thus "function" is distilled down to the simple dash rocket "->", equality is "is" instead of "===", etc.
  • ...adding new keywords to simplify commonly occuring patterns. This includes class declaration, prototype access, destructuring assignments, loops, and many more. Users of Ruby or Lisp will recognize much of this. These concepts are a very powerful way of shortening your code, and the reason that CoffeeScript code is almost always half or less of the size of the generated JavaScript.

For actual examples, there is a long list of learning and demonstrating resources in the how section. If you're eager to see it right now, take a quick look at the official homepage.

So, underneath it all, it's the same old JavaScript. One of the creator's, Jeremy Ashkenas, goals was for there to always be a 1 to 1 correspondence with JavaScript and CoffeeScript. This makes it easy for someone already into JavaScript to adopt CoffeeScript and sharpen his game. It also means that your CoffeeScript can be used with any and all JavaScript library, and that you can use all JavaScript libraries in your CoffeeScript. In fact, CoffeeScript and jQuery makes for a very sexy combination, as this article notes.

 

Why (not) use CoffeeScript?

There are two main advantages to CoffeeScript:

  • The code is more readable. This is not a trivial thing - being able to glance through someone's code and deduce what it does is a very commonly occuring task, and CoffeeScript will at times read almost as pseudo code, clearly communicating the intent. 
  • The code is shorter. This, too, will of course contribute to readability. Not just by taxing less patience - the extra lines that you don't have to write in CoffeeScript are commonly rather abstract and thus hard to decipher, such as loop juggling, inheritance gymnastics, etc.
  • A third, inofficial advantage, significant to my proud self, is that you feel smarter when using it. Being able to more with less was always the badge of the ninja, and CoffeeScript opens up even more ways of accomplishing that (and more ways to abuse it, of course...).

Lets now instead touch on the more interesting subject of why not to use it!

  • It requires new tools. This isn't necessarily a big problem, as many of the popular editors out there have plugins for CoffeeScript already. But finding and installing that plugin is a hoop you have to jump through, and if you're not using one of the editors with a plugin available, you have to invest the time to learn a new editor (which you probably should be doing anyway, as you're likely using an editor without a plugin API). 
  • It introduced a new step in the build process, as the code has to be compiled to JavaScript before it is used (at least for now, see the last bullet below). This is pretty trivial once you set it up to autocompile whenever the CoffeeScript file is saved, but that initial setup still has to be done.
  • It is a threshold in any collaboration project, which most projects are. Even though, for an experienced JavaScript programmer, grokking CoffeeScript can be done in a few hours, it is a few hours that every non-CoffeeScript developer has to invest before he or she can contribute to the code. This will have a serious impact on the amount of people ending up actually contributing. 
  • For runtime errors, you'll get linenumbers referencing the generated JavaScript. Mostly you'll immediately know where in the CoffeeScript code the bug is located, but when you don't it is a real drag: you have to open the generated file, find the line, deduce from the context what CoffeeScript function this correlates to, then find that corresponding section in the CoffeeScript file and fix the error. There are projects in the work to mitigate this (CoffeeScript execution is coming to Firefox, and already present in Rails), but at the time of writing it remains a very real problem.

Whether the pros outweigh the cons is of course heavily situational, depending both on the individuals and the project. 

 

Who is CoffeeScript for?

To me, the answer to this question is very short: it is for someone who already knows JavaScript, and preferrably knows it rather well. Two reasons for this:

  1. If you only know CoffeeScript but not JavaScript (although obviously knowledge in one will spill over to the other), you are very limited in finding use for your services.
  2. Someone who is already well versed in JavaScript is also equally familiar with its downsides. He or she will therefore understand the point of CoffeeScript, and be able to use its strengths even better.

If you're looking to get into web development, CoffeeScript (in my humble opinion) is not a good place to start. Learn JavaScript the traditional way, and when you know it well enough to be annoyed by the verbose syntax (and have thought through the pros & cons above), adopt CoffeeScript!

 

How is CoffeeScript used?

The primary resource for learning CoffeeScript is definitely the excellent official homepage, which is a testimony to good web design. Apart from a very accessible documentation it also has an interactive console, where you can type CoffeeScript code, see the generated JavaScript in real time, and execute it to see the result. The code examples in the documentation uses the same functionality, enabling you to toy around with it for easy understanding.

That said, there are several other good resources for learning CoffeeScript. I've done an inventory below, split into various categories depending on their media.

Books

First and foremost we have CoffeeScript - accelerated JavaScript development by Trevor Burnham was my foremost resource when learning the language. It is published by Pragmatic Programmers, available as both paper book and ebook. Normally, when a book is published on something that has just recently been made available (or, as in CoffeeScript's case, reached critical popularity mass), you'd expect a greedy rush-job. This is not the case here, and it is evident that Trevor has lovingly crafted the book over a length of time. The book assumes previous familiarity with JavaScript, and so focuses on CoffeeScript's additions.

One of my favourite JavaScript books for beginners is the free online book Eloquent JavaScript by Marijn Haverbeke (recently also made available in an edited paper version). He made this available to the public domain, which enabled E. Hoigaard to "port" the book to CoffeeScript, resulting in Smooth CoffeeScript. His book retains the charm and razor-sharp teaching skills from its predecessor, successfully translated to CoffeeScript's concepts. Do note, however, that both books also teach basic programming at the same time, so Smooth CoffeeScript is not just a dedicated syntax-learning resource.

The two now mentioned books stand apart in regards to scope and author-spent time, but there are a few more books I'd like to mention. First off we have Little book on CoffeeScript by Alex MacCaw. It is not as meaty as the others, but very succinct and to-the-point. He also employs a very neat function where, for all CoffeScript code examples, you can see the corresponding JavaScript (by clicking the small grey square in the top-right corner). Alex also adopts the neat new trend of housing the book's code at Github, enabling readers to quickly make pull requests to fix errata.

Finally we have the community-driven CoffeeScript Cookbook, also on Github. As the title implies it is not a narrative book as such, but a recipe collection of CoffeeScript snippets. However it is still worth checking out, and I really like the collaboration initiative (although so far, my contribution is limited to removing a few unnecessary invocation parens).

Screencasts

I cannot not have the Peepcode CoffeeScript screencast on top here. It is a commercial product ($12), but well worth the price. Sometimes, with professionally created teaching products, I find that the money is spent more on superficial production values than anything else, but this is not the case here - although it is a very polished product, it is evident that it is also very well though-ought, and that a lot of testing and planning has foregone the recording. Heartily recommended! You'll also learn some Jasmine unit testing at the same time, just for good measures! There are some teasers on their supporting blog post (which is also well worth reading).

There is a really good introduction to CoffeeScript 18-minute video at screencasts.org (who also have a lot of other high-quality web-related content). Extensive transcript is included, which is something I appreciate. The title is apt, meaning it is an introduction and not a full coverage, but as a starting point it serves it's purpose very well, and it does manage to touch on mostly all important concepts.

If you (like many CoffeeScript adopters) come from a Rails background, there is a good 11-minute episode on Railscast about CoffeeScript basics. Rails knowledge is not mandatory, though, as the video focuses on a walkthrough of a conversion of a JavaScript code to CoffeeScript, explaining the concepts in the process. There are some extensive written-out shownotes here. The video gets extra credits from me for the hands-on approach - the teaching while translating concept works really well!

Charles MaxWood at TeachMeToCode has done an episode called CoffeeScript basics, which is a nice, slow-paced walk through how to get started. If you don't want to download the video, it is also available on youtube here. As the other TMTC videos, it is done in a "live" setting where we see Charles hacking away in the editor. The style is not for all, but for someone who is dipping their first toe into the coffee and want to hear the thoughts of someone else doing the same thing, it is spot on.

The same guys later followed up with another CoffeeScript episode called CoffeeScript - the Cool Parts, which is more or less a continuation of the first video. It is done in exactly the same style, but moves on to the more advanced concepts (mainly inheritance). This episode is available on youtube too.

Tutorials

If you prefer to do your learning through more static means, here follows a few articles on CoffeeScript. First out is the Rocking out with CoffeeScript on the net section (well worth exploring) of tutsplus. It is from late 2010, so there are a few things missing (classes). Still, CoffeeScript has been very stable since then, so what's there is all up to date. The article is also very well written - assuming no prior knowledge, it immediately gives you a context, a pro-con discussion, and then delves into the details to be put into that context. Well done.

Stefan Buhrmeister wrote a short but sweet piece on How CoffeeScript makes jQuery more fun than ever. It is a pretty "standard" CoffeeScript quicklook, but also making the point of how integrating JavaScript libraries such as jQuery is no problem. He also manages to highlight how CoffeeScript makes some aspects of jQuery (iterations, callbacks) just plain beautiful. 

ElegantCode has a nice tutorial series by Jan Van Ryswyck titled Exploring CoffeeScript. They start at the very beginning with installing it, and then holds your hand through getting over the initial threshold. Be sure not to miss the later installments, as they are not linked from the first post! 

For a quick overview, there is a neat article on JavaScriptAtoms called CoffeeScript - the other JavaScript. It's not a language primer, but gives you the context and an idea on what CoffeeScript is all about.

Slides

I'm not a fan of digesting slides without the accompanying talk, but I've found a couple that can stand somewhat well on their own legs, if you want a lightning-fast powerpointy CoffeeScript fix. First off we have CoffeeScript the Awesome by James Hughes, which quickly walks through the various syntactic sugars by peppering you with bi-JavaScript-CoffeeScript code examples. James finishes up by offering some tips for using CoffeeScript in a .NET environment.

Jacques Crocker made a really neat in-browser presentation for SeattleJS (navigate using the arrow keys). Again we see the various features demonstrated through code examples, but they are well chosen and crafted, and you very quickly get a feel for the language. Also, the programming behind the presentation itself is pretty impressive.

Twitter

If found it useful to follow the following two Twitter accounts. First off @CoffeeScript, which is the official account. It is run by Trevor Burnham, author of the book. He is really fast at replying, and - needless to say - knows what he is talking about, so this feed is a great resource when you get stumped while coding. Of course, it is also a good way to keep up to date with what's going on in the CoffeeScript world.

Another good resource for that is @CoffeeScript_m8. They are very quick to pick up and tweetlink to new CoffeeScript-related content popping up, and indeed claim that "Follow us, and you won't miss a thing about CoffeeScript!".

Communities

On StackOverflow, putting the CoffeScript tag on your question will quickly give you a slew of answers. Trevor Burnham is pretty active here too, and in general the responses given seem to be of very high quality.

There are also quite a lot of interesting related content on the CoffeeScript section of Quora.com. Unlike StackOverflow this is not a place for help with code matters, but deals more with higher level discussion. Thus you'll find questions like "what are the disadvantages of using coffeescript", "what kinds of programmer are more likely to use coffeescript over javascript", etc.

You'll also find quite a bit of life in the CoffeeScript google group, both troubleshooting and news relays. 

Other resources

As stated initially, the official homepage is the best and quickest way if you just want to try your hand at some CoffeeScript hacking. However, if you're using the excellent JSFiddle, it might be good to know that they have added CoffeeScript support (albeight a bit hidden: open the Panels panel and change JavaScript to CoffeScript in the dropdown). As JSFiddle can persist code this is a good way of sharing CoffeeScript snippets, if you don't want to create a github gist.

The web-based Ace editor (formerly Bespin) also has syntax highlighting for CoffeeScript.

If you're using Firefox and Firebug, you'd do well to check out the Acebug addon. Among other things, it gives you CoffeeScript straight in the console!

There is an excellent CoffeeScript bundle available for the TextMate editor, maintained by mr Ashkenas himself. If you're using TextMate, picking this up is a no-brainer. You get syntax highlighting, a runtime environment, and can quickly inspect the generated JavaScript. For plugins to other editors, see the list in the wiki of the official coffeescript page.

While not a learning resource, the CoffeeKup project (also see readme file here) is well worth checking out; It lets you declare your markup in CoffeeScript! Sounds weird, and it is, but it is surprisingly elegant, and it lets you do content and behaviour with one single language. There has been similar attempts in JavaScript, but due to the verboseness of that language, the result was always even clunkier than html. Now, with CoffeeScript, the idea works!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Thu, 27 Oct 2011 23:35:00 -0700 Krawaller real-life appearances http://blog.krawaller.se/krawaller-real-life-appearances http://blog.krawaller.se/krawaller-real-life-appearances
A summary of Krawaller's public appearances over the autumn.

First and foremost, Jacob attended Appcelerator's CodeStrong conference. He promised a blogpost about that, but I'm not holding my breath! At the conference, Jacob gave a talk about Kranium, Krawaller's new utility library for Titanium development. The video is available here. He promised a blogpost about Kranium too!

Together with good friends Alexander and Nicklas, we participated in Travelhack - a most excellent hackaton in Gothenburg focusing mainly around commuting. It was a brilliant event, fun and engaging! You can watch a video where all teams present their doings here (we come on at about 1:20).

Finally I gave a speech at SFIS (loosely translated as Swedish Society for Information Specialists), who had a day on mobile technology. I talked about mobile app development. The slides (in Swedish) are available at 280 Slides here, or for those of you who use a pretend browser (IE), the individual pictures are attached in the gallery below.

Here's a Swedish PS for the librarians who were in the audience at SFIS: Jacob, den andra hälften av Krawaller, har lekt med en prototyp för en bokutlåningsapp, vilket jag givetvis borde haft vett att skvallra om för er! Ni kan se en film av den här

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Thu, 04 Aug 2011 05:50:00 -0700 Titanium app for explaining layout mechanisms http://blog.krawaller.se/titanium-app-for-explaining-layout-mechanisms http://blog.krawaller.se/titanium-app-for-explaining-layout-mechanisms
Wrapping our brains around Titanium View layouts!

During a recent app project, I felt constantly hampered by not having a strong enough ninjutsu understanding of laying out things in a Titanium app. How does horizontal and vertical layout actually work? What's the difference between a View, a ScrollView and a ScrollableView? When having too much content to show on screen, do I want the parent or child to scroll? What happens when I have a scrolling child in a scrolling parent?

I constantly had to pause my work to peruse the Titanium docs/kitchensink/sourcecode, or (more often) do some experimenting on the side, regarding stuff that I suspected I really should have nailed down. It felt like doing maths without having memorized the multiplication tables! 

The TiView app

Eventually the added-up frustration got too great, so I set aside some time for grokking and getting comfortable with the API. This resulted in a small Titanium application we call TiView. It has a number of demos, showing on screen what various layout properties will actually result in. Most of it probably already obvious to most of you out there, but I felt it helped me to "say it out loud" in this way.

As stated the app is very simple. It has a number of demos, ordered into categories. The screenshot below shows the current content, I hope to add some more to it before I move on too far: 

Screen_shot_2011-08-04_at_2
Each category then consists of a ScrollableView, where each view is a demo of some layout code. The properties used are displayed inside the laid-out child:

The source code is available in the Git repo here. Have a snoop and see if might be of any help. Or even better, add more demos of your own! It's just 250 lines in a single file, and all the demos are just object literals sent into a constructor function, so getting your own ideas in there shouldn't require that strong a shoe-horn:

https://gist.github.com/1125138.js?file=gistfile1

Android VS iPhone

When we ran the app on an Android, it turned out that there where even more difference in behaviour between the platforms that we had originally thought! Therefore we gave the demos platform-specific descriptions.

This process was hugely informative for us - not only did we gain a better understanding of the layout API:s, but also of the (many) differences between the platforms! Having a good map of these differences will make it much easier to write code that won't behave differently on the other platform.

So we encourage you to try out TiView, and hope it will be of use!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Sat, 26 Mar 2011 01:15:00 -0700 Krawaller's iPad design flow - productivity app recommendations http://blog.krawaller.se/krawallers-ipad-design-flow-productivity-app http://blog.krawaller.se/krawallers-ipad-design-flow-productivity-app
Reviewing our favourite iPad productivity apps!

While waiting for my younger brother to post some long-promised content, I thought I'd give a quick overview of our design flow iPad usage. When I first got my pad, I bought it mainly as a testing device, not really anticipating to use it as an actual productivity tool. Because let's face it, in what fields could it possibly bester my trusted MacBook Pro? 

In quite a few, as it turned out! Obvious as it might be to the rest of the world, a touch screen is a very different input device compared to a touchpad and keyboard. And, as I eventually realised, it is especially well suited for sketching and doing mockups. 

Our design process

We've always done quite a bit of planning before we got our hands dirty in the editors. This planning can take many different forms; napkin scribbles, phone conversations, whiteboard doodling, and sometimes an actual UML diagram. 

This initial sketching would cover all aspects of the application-to-be: program flow, data structures, use cases, and UI layout. Mostly we'd go through several iterations, and only when things began to settle down a bit did we fire up the editors. 

This flow remains the same, but what the iPad has allowed us to do is to digitize the first part. Doing those things on the computer was never an option; it's simply too slow! There are plenty of good mindmap/diagram/software-planning programs for MacOS, but none that can keep up with the speed of thought. 

On the iOS, it turned out, it's a different story, all thanx to the touchpad. Using this input device, you can sketch and mock-up almost as fast as you can think it! 

We never thought of our disorganized doodling as consisting of different sketching paradigms such as mindmapping, flowcharting, etc. It was all something inbetween, crossing haphazardly back and forth between approaches. Now, using iPad apps instead of napkins, this process has broken down into several main areas:

  • mindmapping - organizing thoughts together
  • flowcharting - mapping the flow through a single interaction/function/event chain
  • prototyping - mocking up user interfaces or parts thereof
  • doodling - simple free-hand sketching
  • codehandling - reading existing code bases
  • filesharing - using cloud file handling services

And here follows a quick run through our favourite tool for each of these areas!

Mindmapping with iThoughts

First off: mindmapping. This can be used initially just to sort app ideas together, but also in a later stage to map out the ingredients of the app: UI parts, classes, globals, etc. In essence this is our rebellious interpretation of a UML class diagram, I guess. 

Photo_mar_26_10_30_05_am

To this end, our favourite tool has come to be iThoughts HD. There are a lot of various options, of which I've tried most, but iThoughts somehow just resonates with me. Some favoured features are:

  • Organisation of maps: a fundamental feature, you might think, but it is missing from a surprisingly huge number of mindmapping apps. iThoughts lets you organise maps in folders and subfolders. It is also very easy to base a map upon another, copy them, etc.
  • Excellent export options. And with excellent I mean that it supports our file handling system of choice, namely Dropbox. It can synchronize automatically to a map in the cloud, and also of course export into other formats.
  • Brilliant UI shortcuts throughout, minimizing clicks and gestures. It is very evident that the developers have invested lots of time in making the mapping process as smooth as possible.
  • Perhaps not a feature, but the maps are, with very little effort, rather beautiful! Not a factor to sneer at, and a potential client frequently reacts much better to an iThoughts-generated pdf than to our previous napkin-based charts...

Flowcharting with Instaviz

When zooming in a bit at the process and planning out a user interaction (or even a specific application function), flowcharting is an excellent way to visualize your thoughts. Again there are a multitude of options of which I've sampled most, but the one that stuck out from the crowd is Instaviz. 

Photo_mar_26_10_30_17_am

Instaviz boasts having an advanced layout algorithm developed over the course of decades, and this immediately shows. Not having any control of the actual layout and position of boxes takes some getting used to, but once you have it's really convenient. The algorithm will always (so far completely without exception) find an excellent way to organize the boxes, so that the flow is easy to follow and as few connections as possible cross each other.

Now, there are some irks; Instaviz has no chart organisations (they're all just lying in one huge list, meaning you have to prefix the names with project and milestone in order to navigate), and perhaps worse, there is no way to select more than one box at a time. There are a few other rough edges in the UI as well, such as having to delete the default text in a label, etc. 

But even so the good outweigh the bad, and the app is still in development so it will only get better from here. Heartily recommended!

UI prototyping with Omnigraffle

For laying out the user interface, I've fallen in love with Omnigraffle. In comparison its a hugely expensive piece of software, but in essence you get what you pay for. Omnigraffle is a hugely powerful program, and once you've mastered its (intuitive) interface you'll be mocking up interfaces in no time at all.

Perhaps even more important - through Omnigraffle's excellent multiselection tools it is very easy to manipulate an existing mockup, enabling to try out different layouts as quickly as you can think them.

Photo_mar_26_10_30_25_am

Omnigraffle is based around the concept of stencils, which work a bit like LEGO bricks; there are lots of different pre-made parts (like for instance the various parts of the iOS UI) which you can import into your diagram, letting you quickly scaffold your prototype.

And of course it is also easy draw free-hand objects, when there isn't a stencil within immediate reach that suits your needs.

An indirect negative note: Omnigraffle sells itself also as a flowchart maker, and I've seen examples of mindmaps done with it, too. In both of these fields, however, Omnigraffle really cannot compete with neither iThoughts nor Instaviz.

But, when it comes to prototyping, it really is a beast, and in my mind the rich feature list and easy of use justifies the hefty price tag. 

Doodling with Drawing Pad

Charts and mindmaps and UML and OOAD and software engineering in all its glory - sometimes you just need to doodle! When overcome by that urge, our favourite tool is Drawing Pad. Super-easy to use, yet still surprisingly powerful.

Photo_mar_26_10_29_44_am

There are several more professional drawing apps out there, but for us that kind of misses the mark - our doodle needs are, per definition, basic and immediate, and thus we need a basic and immediate app to fulfill them. Paint instead of Photoshop, so to say. Drawing Pad fits this role perfectly

Coding and code-reviewing with Textastic

As initially stated, we first sketch and doodle and map on the iPad, and then move on to coding on our MacBooks. Sometimes, however, you'll want to hack down some code while doodling, or maybe quickly read/review some existing code in order to know how to proceed with the current flowchart. Then it is convenient to have the possibility to do so directly on the iPad, and not having to change devices.

Photo_mar_26_10_29_54_am

When this happens, we turn to Textastic. Expensive in comparison to its competitors, but again, you get what you pay for. A very nice interface and excellent Dropbox support has won us over. 

But, isn't coding on the iPad rather cumbersome? Yes, definitely, even if Textastic does what it can to easify the experience through extra characters on the keyboard, etc. But the point isn't to compete with coding on the computer (which it could never do), but to provide an ok experience when some instant coding needs to be done in connection with some doodling in the other apps. 

And, as stated above, we frequently find ourselves wanting to read some specific code while planning, and to this end Textastic works perfectly.

File sharing with Dropbox

Ok, so focus was on the design process, but now I've mentioned Dropbox too many times not to give it its own headline. Dropbox is a brilliant tool for sharing files, and especially well suited for the development flow consisting of all of the above mentioned apps. 

Photo_mar_26_10_29_35_am

We'll make a Dropbox folder for our project, and then from the other productivity apps we'll export the result to that folder. For the apps that don't support Dropbox (like Instaviz) we export a photo, which we can then put into the folder using the Dropbox app.

What we're still missing

Perhaps it doesn't sort directly under the desing flow headline, but we still haven't managed to settle for a project management / todo list application. This definitely impedes us, especially since neither me nor my brother are the most organised people to begin with. So, if you guys out there have any favourites, please try to sell us on them!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Wed, 16 Feb 2011 08:00:00 -0800 Titanium application structure – learning from Tweetanium http://blog.krawaller.se/titanium-application-structure-learning-from http://blog.krawaller.se/titanium-application-structure-learning-from
Struct - learning from Tweetanium regarding application structure best practices!

Up until recently, like so many other lost souls, we've followed the same Titanium application structure as Appcelerator's KitchenSink application. In this paradigm, when you want to open a new window, you'd typically do something like this:

https://gist.github.com/829615.js?file=openingwindow

Inside somefile.js the window would be populated with controls, using the Ti.UI.currentWindow reference. We can access the data from the previous window through win.importantdata.

This approach, even when improved upon, has several disadvantages:

  • If you have a file with application helper functions, you need to import that in every other file that needs the functionality. In my Tristania app for example, pretty much every file starts with Ti.include(“../assets/utils.js”).
  • Every time a window is meant to be created, the relevant file must be read and code parsed.
  • The structure of the app becomes rather opaque.
  • It is very difficult to unittest this approach.

It all works, sure, but I've never been comfortable with my application structures, feeling there must be a better way. Even though there are (many) ways to improve on the above example, I wanted a different structure paradigm alltogether. Alas, I was too lazy to get around to experiment with it, so “it remained but a beautiful thought”, as we say in Sweden.

Fortunately, Kevin Whinnery, Chad Auld and the rest of the Appcelerator team have no such character flaws! Recently they opensourced Tweetanium, a fully functioning Twitter client coded with best practices regarding both JavaScript in general and Titanium in particular.

Which was like christmas to me! The only non-Krawaller Titanium source code I've gleaned (with a few none-noteworthy exceptions) is the aforementioned KitchenSink, which – let's be honest – is not a great piece of work at all. It demonstrates the API very well (which is great since the docs are crap), but as an application example, it leaves me wanting.

So, enter Tweetanium. As soon as you open up the sourcecode, it is evident that they're doing things very differently! I have created a stripped-down, barebones version of it called Struct, aiming to expose the new structure paradigm. You'll find the git repo here. This is what it looks like – isn't knowledge beautiful? :)

The main point in the Tweetanium approach is that my various files (like somefile.js in the above example) are not messing with Ti.UI.currentWindow – instead, it augments a global namespace with a constructor variable. In Struct, I end up with the following global object:

https://gist.github.com/829615.js?file=globalobject

The program flow is that the otherwise pretty empty app.js imports struct.js, which can be considered your main app definition file. This file creates the global namespace and maybe some utility functions, and then includes the other files to populate the rest of the namespace.

This means that as soon as the struct.js file is included, the entire app structure is created in memory. No more parsing of files will be done during the session.

App.js will then call the createApplicationWindow function, call the open method on the returned window, and maybe do some other app initialization stuff. Now the app is up and running! In Struct, app.js looks like this:

https://gist.github.com/829615.js?file=app

So what are the great advantages to this approach? I've already found quite a few, but it boils down to a single keyword: closure. Every single function is executed in the same closure (ok, maybe subclosures, but you get the gist). Read that sentence again until the implications set in.

This is good news from a performance perspective (and most likely stability) – no more importing the same file a gazillion times! But from an infrastructure point of view its even yummier:

  • As we always have access to the same scope, we can keep app-wide data in a single object, instead of JSON:ing back and forth with Ti.App.Properties.
  • All kinds of other convenience structures are suddenly very easy to build. In Struct there is a global messaging system, using one single view, instantiated only once. Tweetanium does a similar thing with a loader view, and has a very neat Model baseclass thing going.
  • You can instantiate all app windows and views immediately, as they all live in the same closure. Windows opened at a later point will also live in the same closure, since that's where the constructor function is defined.
  • Creating your own navigation system ("immersive UI", to use Apple's lingo) is a breeze. In Struct I've stolen the home-brewed tabs from Tweetanium.

Now, having autopsied Tweetanium, created Struct and looking at the layout before me, it seems very obvious and self-evident. Perhaps it already was to the rest of you, but for me it was a new-found revelation, and I can't wait to test it out in our next project! So, for those of you who like me hadn't caught on to this train before, check out Struct & Tweetanium and try it out!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Thu, 03 Feb 2011 00:05:00 -0800 Releasing Auktionera, a Tradera iPhone app http://blog.krawaller.se/releasing-auktionera-a-tradera-iphone-app http://blog.krawaller.se/releasing-auktionera-a-tradera-iphone-app
Releasing Auktionera, our iPhone app for the Swedish auction site Tradera!

Update: As Tradera finally saw sense and ported the eBay app, we're pulling the Auktionera app from the App Store! One has to choose one's battles... 

As Jacob wrote the Livetanium post 2 months ago, I remember us vowing to keep up the pace in the content flow to this blog. That was, as stated, two months ago, and this place has been tumbleweeding ever since. Epic fail, as the kids (erroneously) say these days! 

One of our excuses is a pretty intense development of an iPhone app for the swedish auction site Tradera, which is now released to the App Store! Here's a shop link, and we also created a little support site with some more information (in Swedish).

Functionality

The app is a pretty standard auction site app, much like the eBay one. You can peruse auctions, bid, create your own auctions, save favourite searhes / users / auctions, check seller history, etc.

Made with love and care, but pretty boring, in other words. This was also our approach as we entered the project. We weren't really intrigued by the technical challenges, but thought this had a good chance of selling well. This mainly because there already was an app in the store, selling better than our Systemet in spite of being rather crap. 

This competing app is getting flak because of two different things:

  • It is, as stated, rather crappy, being very prone to crash. Also some functions have ceased to work after the latest iOS upgrades. 
  • It relies completely on Tradera's official API, which for whatever reason is missing some vital functionality, such as checking out a seller's previous history. This is, naturally, something that an auctioneer want to be able to do, before taking the plunge and risking those hard-earned dimes!

Our tactic was therefore a mirror image of this list:

  • Make sure the app doesn't crash and burn!
  • Complement the official API functionality with some YQL scraping on the side.

Sounded easy enough, but it turned out that none of the above was as straight-forward as we thought..

Titanium stability

After a lengthy development cycle in Titanium and the emulator, we did a first reality test on an actual device. We weren't really worried, as the app flowed very neatly in the emulator. But, as we fired it up on the phone, we discovered to our dismay that we had managed to copy the very fickleness we wanted to avoid! The app would crash in random places, not leaving any definite clues as to why. 

Not until we ran the app in an emulator next to the activity monitor did we find out why. It turned out that Titanium did some things rather inefficiently, which would eventually cause the phone to run out of memory or processor juice. The same thing happened in the emulator, but there it wouldn't hit the ceiling as soon, as the computer has much more resources. 

So, what were these inefficient things that Titanium did? Well:

  • First off - don't handle XML in your app, unless you can avoid it. XML is of course painful in and of itself, but Titanium's garbage collection somehow cannot clean up after xml parsing. Try it: open a new window, parse some XML, then close that window (using the back button, for example), and watch the processor usage spike, never to drop again. 
  • Be careful when doing advanced table creation. Use the best practices detailed in the documentation, and test your table generation with the Activity indicator running. For some combinations of table gymnastics, the memory usage will be intolerably high, eventually making the app crash.
  • If you have a large data structure, prefer a sqlite database to just keeping a big object in memory. This might be obvious to the rest of the world, but took us a bit off guard - intuitively, we thought it would be more efficient to keep a single object and query that, skipping the overhead cost of a database. However, some testing proved us very wrong indeed - the sqlite database is quicker and uses far less memory.

So we learned some specifics, but the main lesson for us was this: do frequent reality checks on an actual device. Titanium is still a young framework with many rough edges, and some of those edges will not cut you in the emulator since that does not correctly emulate the hardware limitations. 

YQL + Tradera = somewhat true

We also had a rough time with the intermingling of official functionality and our home-brewed YQL-fueled queries. There were several authentication and authorization models involved; the Tradera API requires an App-Id, the user must be authenticated through the API, and also through the official site for our scraping to work. 

When starting off, we had all this in a spaghetti-bowl of code in the app. Lots of moving parts, lots of things that could break at any time. Not until we isolated all of this to a PHP-bridge did the different parts fall into place. This is of course what we should have done from the beginning - separations of concern is something we frequently preach to others. But somehow we fooled ourselves into thinking we'd already done this, as we has lots of logic in the YQL OpenTables. The lesson: you can always abstract your code one step further. :)

API design IS an artform

The biggest challenge, however, was actually using the Tradera API. I now realize that I've taken usability and intuitivity for granted in the API:s that I use, not thinking much of it. It's like appreciating your mom doing all the household chores - you don't, until you move out. I had no idea that designing a good API takes work, until I used a bad one.

Now, you shouldn't bite the hand that feeds you, but the Tradera API is pretty horrid. There seems to be no general rule for naming functions (camel casing, lower case, it's the wild west in there). The same property names mean different things in different functions. Documented properties are sometimes populated, sometimes not, depending on the weather and alignent of planets. Functionality between functions overlap, but never so much that you can ignore one function and just use the other.

And, most jarringly - there are several spelling errors in the API! When first creating our infrastructure to make calls, I tested it using the most simple function "GetOfficialTime", requiring no parameters and just returning a flat data object. It didn't work. Several hours later of reading SOAP specs and going through the code, I found the error - I needed to spell it "GetOfficalTime", note the missing "i". Fast forward a few weeks, and the same thing happened again when we tried to filter out used goods with the search parameter "ItemCondition". It was supposed to be "ItemConditon", again note the missing "i". 

In Tradera's defense, the misspellings are also present in the documentation, and they offer free support for developers using the API, which we found very helpful. But still, it made me better at appreciate good API design. And more on my guard when using them.

The result

In the end we feel pretty proud of the result! This in spite of entering the project with little heart, and being in some serious stability trouble mid-journey. So, now to the boring side of things - pushing the app, spreading the word. As previously lamented, this is not what we do best.

Anyhow, hope the Swedish speakers among you will check the app out! Next up, Jacob will do a (less chatty) write-up on his neat method for deploying app builds to testers, right, brother? The pressure is on!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Wed, 01 Dec 2010 04:16:00 -0800 Livetanium http://blog.krawaller.se/livetanium http://blog.krawaller.se/livetanium
Our latest experiment, Livetanium, lets you do realtime prototyping when creating Titanium apps. For the lowdown on why this is a good idea, check out this article!

We're proud to announce our latest experiment - Livetanium - realtime prototyping for Titanium Mobile.

Made out of titanium, nodejs and unicorns, our Livetanium library lets you code Titanium Mobile apps and see changes in realtime. It uses a nodejs server to pipe filechanges to the app, and these changes are applied in realtime. It's iPhone only at the moment, but works in both the simulator and on the actual device. You can see a quick walkthrough here or check out the source.

Please try it out and let us know what you think!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/395144/jacob_small.jpg http://posterous.com/users/36u9lHV4WwFz Jacob Waller Jacob Jacob Waller
Thu, 21 Oct 2010 02:03:00 -0700 Releasing Tristania fan app http://blog.krawaller.se/releasing-tristania-fan-app http://blog.krawaller.se/releasing-tristania-fan-app
The Tristania iPhone app is now finally finished and available in the App Store!

We are proud to announce the release of our latest creation; the official app for the magnificent metal band Tristania

Screen_shot_2010-10-21_at_11

 

Features:

To get a feel for the app, please peruse the screenshots below:

With the app you can follow Tristania's various digital presences such as the official homepage, Twitter, Facebook, YouTube, gallery etc, from one convenient place. You'll also find a comprehensive discography section with lyrics and band comments, as well as other related band information. Some discussion on the included features can be found in this blog post.

If you're a Tristania fan you probably won't want to read any further, as this blog focuses on the technical side of things. Instead you might want to head on over to this thread in the official forum, where you can discuss the app, tell us of bugs, etc. But, if you're a nerd, read on! 

Used tools:

Although it is unlikely that the average reader of this blog is unfamiliar with any of these JS-Ninja weaponry, here's a quick rundown of the tools used when building the Tristania app. If any of the below is missing from your toolbox, definitely rectify right away!

Titanium

As usual we built the application using Titanium, so that we can program in the language we know and love (JavaScript, as opposed to Objective C), yet still deploy it as a native application. 

Although little brother has extensive experience with Titanium by now, this was my first "serious" deep-dive into the framework. Here are some of the lessons learnt during that journey:

  • The emulator is not to be trusted, you need to make regular sanity checks on an actual device. In particular, what the emulator will not emulate is lag when a table / webview / somedetailedobject is rendered on the phone. Several times we had to refactor our code, when real-life tests revealed a certain solution to be too slow, in spite of split-second rendering in the emulator.
  • Frequently delete everything in the build directory. Yes, this means that you have to perform a full rebuild to test the next iteration, which some extra takes time. But you will save yourself from hugely annoying bug hunts caused by Titanium erroneously keeping old settings in the build. Take extra care to flush build before building to the device, and definitely flush thrice before packaging for upload to app store. 
  • Just ignore the official documentation completely. It is nowhere near complete, and full of half-truths and outright lies. Rely instead on the Kitchen Sink code. While not exactly a shining example of best practices, it has working examples of pretty much everything. When that fails, check the source code of Titanium itself. Also the FAQ discussion on the official homepage is a good resource.
  • Titanium is still a beta-ish platform, and sometimes the boat will be rocking for no fault of yours. But, it is getting more stable by each release, and being able to code native apps in beautiful JavaScript is worth the frustration. 
  • The API is very low-level, as it should be. So for a large application you definitely need some kind of library to keep you sane, lest you have to type out lots of very verbose code everytime you want to create some non-trivial element. We adressed this through a little library of our own, which is slowly making its way to maturity. Especially with the added investment just announced today, things are only going to get better! 

Now, misunderstand me correctly - in spite of the whiny tone of the above notes, I still feel that Titanium is a remarkable framework, and that it is definitely heading in the right direction. 

YQL

Yahoo's web service to transform any online data into beautiful JSON is nothing short of brilliant. I already sang the praise of this service in the in-progress post, so shall not reiterate that here. The main point for us was to be able to isolate fragile scraping logic outside the application, in a YQL OpenTable. Should the site we scrape change its markup, we just update the table, and all apps will instantly work again. Also, being able to pass pure JSON back to the app is wonderful, making for a beautiful separation of concerns. 

CouchOne

This is another road that little brother paved for me, as he has used CouchDB in both Golingo and Systemet. For me, however, it was a completely new experience.

Screen_shot_2010-10-21_at_12

What's special about CouchDB is not just that it's all JavaScript emitting JSON (which in and of itself is really cool), but it is a (for me) whole new way to think about data. The veterans among you are probably wrinkling your noses over us youngsters never having heard of MapReduce before, but somehow I've managed to completely miss this database approach. In a MapReduce database, data isn't organized in tables. Instead it is all "documents", meaning a simple object of key-value pairs. Here, for instance, is a user document from the Tristania database:

http://gist.github.com/638246.js?file=document

Since there are no tables, you cannot simply "SELECT * FROM Users". Instead, you program a "view", using JavaScript. Every document will be sent as an argument to a "Map" function, where you choose what to emit to the result set. The result will be a JSON object with a rows array, containing all the emitted objects. Here is the map function from the users view:

http://gist.github.com/638246.js?file=community

This might sound wasteful - so we have to go through all our data, even though we're only interested in a particular well-defined subset? Somehow, however, CouchDB mitigates this, due to the way the data is stored on disc. It also remembers the result of passing a certain document to a certain map function, making the database every bit as fast and resilient as its table-based counterpart.

Another view in the Tristania app is the Statistics view, which also uses the Reduce function to return a single, aggregate object:

http://gist.github.com/638246.js?file=statistics

The result the same JSON structure as before, but the rows array now has only one value:

http://gist.github.com/638246.js?file=result

Still early days for the app, so as you can see above, it needs a lot more votes for the statistics data to be meaningful.

As with the notes on YQL etc, this isn't meant to be a CouchDB primer, but merely a way to wet your appetite if you still haven't made its acquaintance. 

GitHub

So here we are definitely preaching to the choir, but I just wanted to put it to protocol that without Github, we never would have made it. We're situated in different parts of Sweden, and have been working in parallell on different parts of the application. Here's a snapshot of our Github app Network graph, showing our intertwined commits: 

Screen_shot_2010-10-21_at_11

In our horrid pre-using-version-control days, we never could have pulled this off. Github for president!

PS

And, we know we've said it before, but it cannot be said too many times - go buy Rubicon, Tristania's new album! Now! :)

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Sun, 10 Oct 2010 02:21:00 -0700 Book review - JavaScript Patterns http://blog.krawaller.se/book-review-javascript-patterns http://blog.krawaller.se/book-review-javascript-patterns
Does Stoyan Stefanov's latest book deserve a place on the bookshelf of a JavaScript ninja, in spite of having a partridge on the cover? Read on to find out!

Back in April, Yahoo's JavaScript guru Stoyan Stefanov set a very ambitious goal for himself; to publish 5 books before the end of the year. An amazing feat, even when accounting for his generous definition of the task.

So, how did he fare? Well:

  1. His "High Performance WebSites for dummies designers" book titled Speed Matters has been postponed to January 2011...
  2. ...and there's no sign of the promised 2nd edition to 2008's Object Oriented JavaScript...
  3. ...nor the "CSS for web devs" project.
  4. But - his participation in Nicholas Zakas' High Performance JavaScript worked out beautifully, as previously extolled on this blog...
  5. ...and now, O'Reilly has released JavaScript Patterns (JSP), a solitary book project from Stoyan on design and coding patterns in JavaScript development.

Javascriptpatterns

Does this book deserve a place on the bookshelf of a JavaScript ninja, in spite of having a partridge on the cover? Read on to find out!

Assumed knowledge

First question, is it at all meant for the ninjas? The book claims to be "targeted at professional developers and programmers who want to take their JavaScript skills to the next level". That's all well and good, but we've been let down by such phrases before, when the authors didn't want to lock out the much bigger and therefore more profitable beginner / intermediate audience, and so diluted the advanced concepts with lots of basic cruft. 

This, however, does not happen in JSP. Stoyan states in the preface that the basics not tying in directly to the ongoing discussion will not be covered at all, and refers instead to a list of suggested reading for those not feeling prepared enough. And throughout the book he stays true to this mission statement, consistently assuming that the reader is well versed in both JavaScript and general programming paradigms

This makes for a very rewarding read, where focus is kept on the matters at hand. That's not to say that it will all be new-found revelations - the first chapter presents JavaScript the language, and the second chapter (titled "Essentials") goes through the established canon of best practices. However, the former is but a few pages, and the latter is so succinct and well-written that I still felt rewarded after reading it, even though I've heard (almost) all of it before.  

The "Pattern" concept

Now, I've been looking forward to JavaScript Patterns (JSP) ever since Stoyan's initial announcement, but the title also gave me some concern - books that are forced into an artificial mold rarely sit right with me. Take the similar cookbook approach, with the jQuery Cookbook as a somewhat recent example - while the recipe structure has its merits, that book and most of its likes would be better off organized as a "normal" book on the subject.

There's no major difference between the jQuery Cookbook and, for example, jQuery in Action. They both strive to be an all-covering go-to resource for jQuery development. But while the latter is cleanly organized and easy to use, the former is marred by the recipe concept, which sometimes seems to mean "very specific task", and then in the next chapter it is suddenly synonymous with "this broad subject". 

As given away by the title, Stoyan's book is organised in a similar fashion. Here, however, the mold fits the text like a glove. In no small part thanks to the fact that the author takes great care to define exactly what he means by "pattern", what different flavours he considers the word to encompass, and how this applies to the structure of the book. In the case of JSP, the mold is not a populistic way to make it seem more accessible, but an honest and successful attempt to organise the information.

Also, Stoyan isn't a slave to the structure, and doesn't feel forced to include the word "Pattern" in every headline. When he sees the need to break the mold he does so.

How VS why

Also, a proper pattern collection / cookbook would probably be more like a phrasebook - serving finished solutions without explaining the nuts and bolts, and thus be of little interest to people actually wanting to learn the language. I've always shunned such books, finding that I have shorter journey if I take the time to equip myself first with an understanding of the basics.

Stoyan has had a recurring column in JSMag titled "JavaScript Patterns", in which we've been served snack-sized previews of this book. In the magazine, however, there isn't much room to elaborate on the context, so the articles in question has mostly consisted of inventorying the different ways to accomplish something (how to define an object literal, how to define a function, etc). Recipes, you could say, or phrases, if you're in a worse mood. While interesting on an academic level, I rarely looked up from one of those articles thinking "hey, I can use this". They justified their own existence, they explained for the sake of explanation, but without much connecting discussion about real-world application. 

And that was my fear - that the book, like the articles (and OOJS, to a degree), would list the different ways to create an object / emulate class inheritance / bind a function to a context / etc, without providing discussion or meaning. But, as previously stated, JSP is very different from the articles. Stoyan gives ample room to discussing the why, and all (well, most) patterns are defined with a clear goal and a problem space. We're not simply being told "42", but also what the question in question actually is.

A prime example is his chapter on inheritance - he opens it by stating that code reuse is the objective, and that the dynamic nature of JavaScript provides other and easier means to achieve that end than the classical inheritance of strongly typed languages. In fact, the chapter isn't even called inheritance, but code reuse. He of course covers emulating classes, but in a context of discussing the (lack of) merits of that approach compared to other available solutions.

Comparisons

Here's a few comparisons between JSP and some other tomes you might already have:

  • Pro JavaScript Design Patterns: PJSDP is an excellent book, in which Ross Harmes and Dustin Diaz sets out to convert the design patterns popularized in the game-changing Design Patterns: Elements of Reusable Object-Oriented Software into JavaScript. This, however, means focusing on a classical approach borrowed from languages with strong types and interfaces. We might be feeling at home with that, but we would be better off embracing JavaScript's dynamic, loosely typed nature, and find solutions that work best in this environment. This is what JSP provides. And, JSP discusses "patterns" in a broader sense - where PJSDP is only concerned with design patterns, JSP hovers higher and also talks about coding patterns, meaning paradigms in a wider sense; best practices, work flows, approaches, etc. I will continue to enjoy PJSDP, but JSP is where I'll go for real-world help.
  • High Performance JavaScript: There is some overlap here, as JSP adresses some patterns regarding performance. These are all also found in HPJS, covered in greater detail. But mostly the books live in different problem spaces, and there's no reason not to have both in your shelf. 
  • Object Oriented JavaScript: OOJS has already been unfavorably compared to JSP several times in this review. There is a lot of overlap between the two, but where OOJS sets out to verbosely explain everything about object-oriented JavaScript (and everything you need to understand that explanation), JPS adresses only the bits relevant to the discussion at hand. JPS is way more succinct, and because it assumes you already have a good foundation, it can afford the luxury of high-level discussion. So: they are very similar, but JSP is the more mature of the two, speaking to a more experienced audience.

The bottom line

I enjoyed JSP even more than I thought I would. Through being one of the few JavaScript books that dares exclude the beginner crowd completely, I would buy it no matter what. But it is definitely worth reading also from its own merits, as it is full of thoughtful discussion that is bound to expand your horizons even if you are a very seasoned JS developer. So - go get! 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Mon, 04 Oct 2010 11:19:00 -0700 Jumping onto the PromoteJS bandwagon http://blog.krawaller.se/jumping-onto-the-promotejs-bandwagon http://blog.krawaller.se/jumping-onto-the-promotejs-bandwagon
Krawaller supports the commendable PromoteJS initiative!

The PromoteJS project strives to make a web search for JavaScript documentation yield better results than snippets from '95 full of bad advice, and W3Schools syntax definitions void of explanation. This is done through promoting Mozilla Development Center's splendid JavaScript documentation.

It's a fair guess that the readers of this blog already know all about this stuff (if not, go read Christian Heilmann's excellent explanation), so we shall not waste time preaching to the choir but simply do our bit for the SEO lobbying and link to the Mozilla documentation for JavaScriptString, Function, Array & Object.

PS: If you haven't already made yourself at home at the MDC site, do! The JavaScript documentation isn't the only worthwhile thing there, they have plenty of tutorials and posts with high quality throughout.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Thu, 30 Sep 2010 05:10:00 -0700 Book review - JavaScript Testing http://blog.krawaller.se/book-review-javascript-testing http://blog.krawaller.se/book-review-javascript-testing
Reviewing Packt's latest offering on JavaScript testing. Ninja lore or newbie lark? Find out here!

Book-jstesting

Before we start off, I must admit to my purchase being a badly researched one. I saw the title of this book glancing by in a Packt ("Since you bought X you might be interested in Y") email, and clicked the Purchase button before realising that this book has absolutely nothing to do with Test-driven JavaScript Development that I was really setting out to buy. However, aspiring to be well versed in JavaScript literature in general because of the JavaScript course I hold at Linnaeus University, I didn't cancel my order. Had I bothered to read through the Table of Contents more throroughly, I would have.

JavaScript Testing - A Beginner's Guide, by Liang Yuxian Eugene, is a very strange beast. It assumes no prior knowledge whatsoever, and so sets out to explaining everything from basic JavaScript syntax and programming paradigms (without separating the two) to how JavaScript fits together with HTML and CSS. All this is done with a focus on testing, but taking care to explain everything as it goes along. This makes for a very peculiar read for newbie and ninja alike.

Mundane content aside, the book is very verbose, to the point of the forest being lost among the trees. For example, the author spends an entire page (chapter 3, page 95) explaining how to fix the "error" of JSLint complaining about "unexpected use of ++". Not with a discussion about the pros and cons, but by repeating a huge chunk of code, the first using ++, then changed to +1. There are definitely times when being verbose helps getting the point across, especially when trying to communicate the basics of a paradigm new to the receiver. What's going on here, however, is pure page bloat. Considering that the book is only 250 pages total, that does not paint a flattering picture of the weight of the actual content.

The book is also suffering from the usual Packt flaws;

  • The typesetting is really strange. I realise that smarter people than me has considered the made choices, but I'll never get used to the strangely fat, seriff-lacking font used for the basic text.
  • Since they often have several headlines on each page, the bloated Table of Contents is rather useless, providing no overview. I really miss Apress' "Contents at a Glance" concept, which is sorely needed here.

In all fairness, the book does has some merits. The testing focus equips the reader with a good set of best practices, building up a good workflow which makes for less headaches during development. I gave the book flak for being too verbose, but I guess you could also argue that it is rigorous.

There is, however, nothing in there for the more advanced reader (which the subtitle "Beginner's Guide" partly excuses, but nevertheless). Unit testing gets a brief mention, but in a context that makes it seems rather periferal. Debugging with alert, if you judge by the number of devoted pages, is much more important according to this book.

I feel the basic problem with the book is the premise - it targets a complete novice, aiming to teach him JavaScript, programming and development planning, all done with a focus on "testing". But, if you don't know some or any of these field, the content in this book is nowhere near enough. And if you DO know them, and just want to hone your testing skills and mindset, the avalanche of superfluous information will keep you from doing so.

To conclude: there are some good advice in there, but they would come more to their right as a (much) shorter tutorial article.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Sat, 04 Sep 2010 03:56:00 -0700 Headbanging with YQL http://blog.krawaller.se/headbanging-with-yql http://blog.krawaller.se/headbanging-with-yql
Discovering YQL's inner heavy metal!

Tristania-7406

During the past month, we've been hard at work on the official application for the metal band Tristania, a project now nearing completion. This process has given me much food for thought, and a new love of my life - Yahoo's YQL tool!

Band app content

As the specification for the project was rather vague (us: "do you want an iPhone app?", Tristania: "yes please!"), the first step was to figure out what such an app should contain. There aren't really that many "band apps" as such in the app store, so no precedence as to what a normal band app is has been set. That left us pondering:

  • Tristania have several digital presences such as the official homepage, a forum, a myspace site, a youtube channelfacebook pagetwitter account, a separate fanmade picture gallery, etc. Shall we pull in content from any of these other online sources?
  • Should it be used as a promotional platform for their new album Rubicon
  • Should the app have unique content not found elsewhere? 
  • Can we somehow put in some functionality that actually uses the platform, to preemptively answer the question "why not simply surf their homepage in Safari"? 

In the end, we answered these questions with "Definitely", "Sort of", "No" and "Hopefully". 

As the "Definitely" suggests, data aggregation became the main justification of existence for the app. As we pull in data from almost all the aforementioned Tristania web resources, the application is a way for the fan to easily stay up to date with what's going on. Granted, it doesn't take that many extra minutes to manually check these different sources in a browser, but it still gives the app a sense of function.

The "Sort of" regarding promoting Rubicon is simple - we made a spotlight function where individual data from the different sources can be promoted. Right now we have Rubicon-related data in there, and as the next album draws nearer we'll promote that instead. This turned out to be an easy way to keep the content fresh and helping the band out, all without denying access to older content or having to code complicated extra functionality. 

Regarding the "No" to unique content, we've had to rethink our initial plans. Tristania used to be pretty bad at communicating with their fans, and their official homepage has traditionally been very stale and rarely updated. I therefore thought the app might be a way of getting them to share a bit more on what's going on in their world, allowing us fanboys to peek over their shoulders. Lately, however, something has happened - now they're suddenly very active on lots of different fronts (as seen in the list above), giving the fans fast and easy access to the goings on in the band. Therefore the need for an accessible information platform has been fulfilled already, and our application can take a back seat with a clear conscious. 

Finally the "Hopefully" - we have a plan to use geolocation to display all the app users on a map, and upon clicking a pin, showing that user's presentation and favourite album/track (which can be set in the discography section). This, we thought, was a nice way of tying things together, as well as actually putting the platform to use. We felt from the beginning that we need some kind of interaction, to prevent the app from feeling like a webpage crammed into the phone. We're still not sure if we'll manage to piece this together for the first release, hence the "Hopefully" instead of "Oh yeah".

YQL to the rescue

As seen above, most of the code in the app has to do with collecting and displaying external data. This has many similarities to what little brother Jacob did in his Swedish app store hit Systemet. He there put YQL to good use, and repeatedly sang its praise during the development. I never really understood what the fuss was about, but then again, I didn't really understand exactly what problem YQL solves for you, either. Of course I've seen the blog posts, read the JSMag articles, and yes, heard little brother nag, but I never saw the big picture. 

Now, as Tristania was mainly my project, I decided to try it out for myself. And, to make an already too long story short; I'm in awe. YQL does all the boring parts for me! I've just built the most extensive data collection application I've ever done, and I have almost no backend - YQL simply eliminates the need!

I realise I was slow to get a seat on this band wagon and that I'm preaching to the choir, but the meaning of this blog post is simply to join the choir and sing YQL:s praises. It's an absolutely amazing product! During this project alone, I estimate it has saved me, what, maybe 20 hours of (really dull) work. You do the math - I already owe Heilmann & co quite a hefty amount of money!

In an attempt to go more easy on the fanboy praise and become more concrete, here's what YQL has done for me in the Tristania application:

  • It is, in essence, my backend. In the application I'm collecting data from several different sources, which I would then normally have to parse and scrape to get what I want and translate to a suitable data format. This is now all instead done by YQL - I simply point it at the correct location, give it a few instructions, and my app is fed with a beautiful JSON object containing exactly what I want. Even when you have a "good" data source, such as Tristania's homepage's RSS news feed, you'll still save time by piping it through YQL to get the JSON structure. Granted, I could do that locally, but now I don't have to! Of all the aforementioned data sources, only the facebook data isn't piped through YQL. Facebook's Graph API returns JSON text, which I can digest in the application through a simple call to JSON.parse. Everything else, YQL prechews for me.
  • Also, YQL enables me to separate concerns and have several fragile moving parts outside the application, through using what they call a Data Tables. Data tables enables you to keep the html-depending logic in an external xml file, which through mingled JavaScript and xml (in a mind-blowingly elegant and easy solution where xml nodes are first-class citizens) defines how the parsing should be done, and what should be returned to your application. My parsing of the picture gallery especially is rather complex; the html is several layers deep, and I need to perform lots of gymnastics to figure out what's what and what I need. I could make YQL give the application the entire HTML structure in a JSON object and do the gymnastics locally, but that would mean that when the Gallery html changes, the application would break, and stay broken until we've submitted an update to the app store. Not an ideal situation. But when using Data Tables, if the Gallery changes, I can simply edit that xml file, and the applications will all start working again. 

So: If you are even slower than me and still haven't caught on - try out YQL immediately, you won't be sorry. If this was all old news to you - why the heck didn't you let me in on it earlier? 

Also, buy Rubicon, Tristania's new album, which rocks.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Sat, 31 Jul 2010 00:11:00 -0700 Pretty Search for Mobile Safari http://blog.krawaller.se/pretty-search-for-mobile-safari-0 http://blog.krawaller.se/pretty-search-for-mobile-safari-0
We're releasing a bookmarklet search utility for iOS Safari, bringing the convenience of the desktop search functions into your phone!

Hey folks!

We got tired of not having any decent Page Search in iOS, so we did what any programmer with self-esteem and too much time would do, and wrote a bookmarklet to overcome this shortcoming. It's still an early release, but it seem to be working, knock on wood.

Prettysearch

Get it

Please try it out by hitting this page and follow the instructions. Unfortunately we cannot programmatically add bookmarks, so you'll have to jump through some hoops. Curious? Feel free to have a look at the source code repository here.

 

What it does

This is a bookmarklet for iOS devices which lets you search the current page using a search string or a Regular Expression. It highlights the matches and lets you jump between them, and the bar follows you around the page. Also, the search is carried out asynchronously, so your browser won't freeze. On top of this, it uses a new nifty caching system to work instantenously, even when offline, yet it is automatically updated whenever a new version is released.

 

How it does it

An interesting point in the creation of this bookmarklet was that we developed a brand new way of handling bookmarklet resources caching and auto-updating. The solution is pretty cool if I may say so myself. It relies upon some new HTML5 features - namely window.postMessage and Cache Manifests. What we do is the following:

When the user taps the bookmarklet, it creates a hidden iFrame pointing to our cache, http://79.99.1.153/prettySearch.js/cache.html.php. This file is dynamically generated to contain all the bookmarklet's resources as embedded non-active script tags, and since the file has an accompanying Cache Manifest (which is also dynamically updated whenever any of our resources are updated) it is saved on your device. So when we load it, it loads from the local cache. If the device is online, it also checks if the Cache Manifest is updated, and only if it is it updates the cache. When the cache file is done loading in its iFrame, it uses window.postMessage to send the resources over to its parent - the page you're currently visiting and would like to search.

This setup means that our bookmarklet only needs to contain the code to bootstrap the iFrame and evaluate its resources. Also, these are loaded instantly from the local cache, and then we automatically check if the cache needs to be updated and does so if applicable. This check only occurs if the device is online, so otherwise it will just happily execute the bookmarklet from cache even when you're offline.

I'll probably write another post about this later on. I think it's a pretty nice hack and I haven't really found any disadvantages yet. Please ping me if you do!

 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/395144/jacob_small.jpg http://posterous.com/users/36u9lHV4WwFz Jacob Waller Jacob Jacob Waller
Sat, 17 Jul 2010 06:07:00 -0700 Building a Titanium JavaScript library http://blog.krawaller.se/building-a-titanium-javascript-library http://blog.krawaller.se/building-a-titanium-javascript-library
As our hands get dirtier still in Titanium land, our convenience abstractions are slowly growing into a full library (whatever that means).

As were finally starting to get some real hands-on experience in Titanium application creation, we've now amassed a fair share of tools to ease the process. The Titanium API is very low level - which is as it should be, but it can at times feel more than just a little clunky. Getting around that is as simple as abstracting away the parts you don't like, which has resulted in our own Krawaller JavaScript framework sitting on top of Titanium. Its nowhere near all-covering, life-altering or complete, but some ideas have come far enough to be thrown at the community, to see what comes back. :)

Below are a few examples of things we've done to ease the process. I'm sure there are several similar and presumably superior wheels invented all over the place - don't hesitate to share your own efforts in the comments!

Element creation logic

We have wrapped all element creation through our own K.create function. The argument object will, apart from the normal parameters passed on to Titanium, have a type and a children property. The type is of course the type of native element, and children is an (optional) array of subelements to be contained within the created element. The create function will recursively call itself and add these to the returned object. This enables us to for example create a TableView like this:

http://gist.github.com/478333.js?file=framework_tableview

We're also sprinkling some convenience logic throughout this function - for example, children of a tableview or tableviewsection are assumed to be tableviewrows if no type is specified, enabling us to leave that property out if it is a row we want.

Created elements are also given access to the object that created them, meaning we can later on access the id property in the above example within a clickhandler set on the rows.

Styling native elements

Another advantage of wrapping the native creation functions is that we can centralise the element styling. A call to our create function results in the execution of something like this:

http://gist.github.com/478333.js?file=framework_createwin

The K.merge function simply merges all arguments together into one object, giving precedence to leftmost properties. Thus, the object you pass in to the create function is always king of the hill, and the options you leave out will get its values from the preset defaults.

Those values all reside in one single object, where it is very easy to quickly give the whole application a different set of clothes:

http://gist.github.com/478333.js?file=framework_defopts

The url-specific defaults are used when creating windows, allowing us to specify specific styles for different pages.

Webviews

Most of the work, however, went into the webview creation function. While recently working on the official Tristania application we needed several different webviews with slightly different properties, which made the code everything but DRY. With the framework in place, however, a single statement sufficed for each webview:

http://gist.github.com/478333.js?file=framework_webview

The argument object has two properties; the name of the template file, and a data object that will be supplied to that template. You can also optionally specify a masterpage, if you don't want the default one to be used.

The call to the creation function takes care of everything, leaving that single execution line in the application code. Here's the definition of the webview creation function:

http://gist.github.com/478333.js?file=framework_createwebview

A template file looks like this:

Being able to write JavaScript logic inbetween the html tags greatly simplifies adding custom behaviour depending on the data.

The master page is a full html document, into which the template will be injected and rendered:

This system has several advantages:

  • The code will be far less dry, and each webview template need only contain the actual html used.
  • Styling is centralised to the masterpage, enabling you to have a global css file linked at one single place. Should a template need specific styling, you can simply add that in a style tag within the template itself, as in the previous biography template example.
  • You also control the rendering of all webviews. This masterpage contains a neat effect where all webviews are initially transparent, but will fade into full opaqueness when it has finished rendering. This looks nice, and prevents the user from seeing it rendered bit by bit.

Going forward

Our plan was never to build a full framework, but putting our various convenience functions together and making then conform has started to amount to the same thing. We're not committing to any "soon" promises, but definitely plan to share what we end up with. I'm not sure a single, jQuery-style-all-conquering framework is what the Titanium community needs, but we could definitely benefit from sharing what we've done to make everyday Titanium life easier. Perhaps this is one way of accomplishing that?

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Sat, 03 Jul 2010 23:56:00 -0700 Systemet http://blog.krawaller.se/systemet http://blog.krawaller.se/systemet
Announcing the release of our new app! Behind-the-scenes bean spillage to follow.

Yeay!

Produkt

We just wanted to let you know that our third app, Systemet, just went live in the App Store. It's an inofficial guide to the Swedish Alcohol Retail Monopoly Systembolaget, and it lets you:

  • Search for nearby stores
  • See store opening times
  • Call the store directly
  • Search for products
  • Sort by name, price and other properties
  • See product info, qualities, suitable recipes etc
  • Find the closest store with a certain product in stock
  • Save your favourite stores, products, searches and recipes

 

We'll spill all the beans about the development of Systemet later, but I can tell you right now that it took some serious Titanium, HTML5, and YQL wizardry to make this happen, and that our "database" is a plain ol' Google Docs Spreadsheet.

Curious, ha? Stay tuned!

 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/395144/jacob_small.jpg http://posterous.com/users/36u9lHV4WwFz Jacob Waller Jacob Jacob Waller
Sat, 03 Jul 2010 01:42:00 -0700 Puzzle app step 3 - revving up the engine http://blog.krawaller.se/puzzle-app-step-3-revving-up-the-engine-0 http://blog.krawaller.se/puzzle-app-step-3-revving-up-the-engine-0
Having finished the level analyser, work starts on actually finishing the game. Read up on the process and try out the playable prototype here!

Excusing the sound of silence

And suddenly a whole month went by! But we haven't just been idling around playing Carcassone all day (at least not just) - this past month has seen several wheels being set in motion;

  • An iPad/iOS4-friendly version of Golingo is waiting in the wings! Come on, little brother, type faster!
  • We're awaiting Apple's approval for our next AppStore application [edit: app is now live, read announcement here] - an inofficial app for Systembolaget (where swedes go buy their alcohol, since we're not trusted to do so without government supervision). There already is one on the market, but our not-so-objective opinion is that we blow that out of the water since Titanium > ObjectiveC (and also good design > bad design).
  • Communications are underway with the manufacturers behind our very favourite boardgame regarding taking it to the iPad/iPhone (inspired by the brilliant appification of Carcassone, which we're absolutely not playing all day all the time). Hopefully we can spill some more beans on that in the somewhat near future!
  • Continuing the trend of placing ourselves at risk of severe starstruckness, we've also begun development of the official app for our favourite metal band. Huge amounts of fun, and having an excuse to communicate with these long-time heroes of ours is simply awesome. Further beanspilling to follow here too [edit: check the related posts here] . 
  • Our biggest pastime, however, has been involvement with a very promising startup, spearheaded by a driven entrepeneur duo with a great idea and the know-how to make it happen. Seeing these guys in action has been a privilige; we might have some badass technical knowhow, but direction, ambition, organisation, efficiency and all those adjectives - not so much. So being able to piggyback on them has been a very educative ride. And, you guessed it; more beans later. 

All this action invariably meant less playtime for our less serious (read: turnover-potent) inhouse project, which demoted our puzzle game to the back burner. But before Carcassone took us over completely things got too busy, we did managed to make quite a bit of progress, which is what we wanted to share in this post!

Analyse this

First and foremost, the analyser module is finished. It turned out to be an almost AliceInWonderlandesque journey into some rather esotheric recursive gymnastics, so if you're into that sort of thing, do dive into the code and check it out (the code repository can be found here, if we haven't already said so).

The idea is detailed in the previous posts, but mainly the idea was to have all game logic in an analyser function that calculates all possible states in a level, including the transitions between these states. The actual player module (yet to be finished, but a scaffold is up) therefore doesn't need to contain any logic, but simply renders the different states and moves the player between them as he gives his commands. This backward design means...

  • Beautiful separation of concerns in the codebase
  • We can programmatically check the integrity of a level, to see if it's actually solvable
  • Better yet, we can also calculate the difficulty, by checking
    • the minimum amount of steps needed to reach a perfect solution
    • how many different branches there are
    • frequency of dead ends and deathtraps
  • This also means that we can include a level editor in the game, and give immediate feedback to the level designer.
  • With some work it should also be possible to randomise levels.

Prototyping

Ok, enough babbling - here's the game in action (if the iframe doesn't play nice, here's a link directly to the demo), using our scaffolded and not-that-lovingly crafted player module. The level isn't that interesting, but serves its purpose as a proof of concept rather nicely. Rule-wise it is very simple; whenever you make a move, all player marbles will fall as far as possible in the chosen direction. 

Here's a quick rundown on the different objects in the level:

  • The yellow marbles are your player objects, which you move with the arrow keys (or touches if you're on an iphone/ipad). The game keeps going as long as at least one marble is still in play. In this version, nothing at all happens when two marbles overlap, as we couldn't decide if they should block or kill each other.
  • The goal is to get them all to the red heart (the meaning of life is love?). 
  • For a perfect solution you must also pick up all the valuables, of which there're two kinds:
    • A small coin, which is simply picked up as you pass over it
    • A large star, which is picked up but makes the ball stop in the process. 
  • The blue rotating asterisks are teleports, which immediately moves the marble to another position (but doesn't interrupt the motion).
  • The blue square is a block of ice, which will gradually break as you collide with it, needing two hits to disappear completely.
  • We're not quite sure what the yellow sun symbol is supposed to represent, but it stops the marble upon entry.
  • The green triangle is a locked door, which is impassable until you've collected...
  • ...the green digit 1, which is a key.
  • The curved wall will of course change the direction of the marble accordingly.
  • The red arrow can only be passed in the direction it is pointing, all other paths are blocked. Not sure if it is intiutive for it to block just the opposite direction or all three non-pointing directions, the jury is still out on that.
  • The grey square does nothing except blocking, and is thus pretty uninteresting and useless. We'll most likely not use it further.

The data structure in action

None of these behaviours are hard-coded into the game logic. Instead they're all defined in the level data object, which is made possible due to the abstract design we laid out in the previous post. Now, whether or not that was a good idea I'm still not sure, since it made the engine tougher to code. It does however allow for a lot of agility now, as it would be easy to think up a new labyrinth denizen and define its behaviour with pure data, without having to touch the logic code.

The behaviours are in essence a description of what will happen upon the collision of two objects. For example, here's the definition of a collision between a player marble (plr) and a key square:

http://gist.github.com/459206.js?file=collision-key

Collision with the gate then looks like this:

http://gist.github.com/459206.js?file=collision-gate

While not rocket science, this system allows us to easily accomodate these new ideas as they come along. The initial idea was to allow the level editor to define new objects here, but probably we'll stick with predefining lots of objects, and limiting the editor to choosing between these.

The missing pieces of the puzzle

Obviously, there's still a long way to go before we have anything close to a finished product:

  • Although a little slab of (CSS-only!) paint made a huge difference, we need to work on the graphics. We're not at all sure how to approach this, but it will definitely still be CSS3-based as far as possible, meaning a simple yet hopefully elegant design.
  • We still have to make the app infrastructure to contain the game.
  • The aforementioned level editor is probably a rather huge project in and of itself, so that will also take some time.
  • As is the randomiser, if it is at all possible.
  • We also need some more ideas regarding in-game objects. Having multiple player balls is a good one, but we need to freshen it all up some more. Balls travelling against gravity, pushable boxes, the list goes on and on.

And since all the excuses we made at the beginning of the post applies for the foreseeable future as well, completion of the labyrinth puzzle game is definitely far off. But, we're slowly but surely getting there!

Also, again: Carcassone is a brilliant game! The application rendition really does the real-life counterpart justice. Buy it, play it, send fan-mail to the developers! 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Tue, 18 May 2010 13:09:00 -0700 Opensourcing Golingo http://blog.krawaller.se/opensourcing-golingo http://blog.krawaller.se/opensourcing-golingo
Come on in to the Golingo Source Release party! There will be stripping! (open sourcing of code, that is...)

Hey folks! Thanks for sticking with us even when we're not the fastest guys around. I'm rea-he-lly glad to give you this promised behind the scenes post of how Golingo came to be. In case you've been sleeping under a rock (without any means of browsing the intertube), here's a quick recap for you: Golingo is our rudely addictive word game for the iPhone - it was released about a month ago, as one of the first to use the totally revised 1.0 branch of Appcelerator's Titanium Mobile. It is currently the #1 word game in the Swedish App Store. Fun stuff!

If you're not at all interested in how to create top paid apps using only Titanium with JavaScript, HTML5 and CSS3, this post not for you. Otherwise, please go ahead!

The code is hosted here at our brand spanking new Github account. Hold your horses or check it out straight a way!

Golingo

But let's start from the beginning. Golingo was born from a thoroughly cosy word game played using Scrabble©-tiles at Café Agape in the tiny Swedish fishing village of Bovall. We've tried to create an electronic adaption that stayed true to the concept of a blazingly quick, enthralling word juggling game. But how did we do it? Come along!

The first experimental version was created as part of a school project back in 2008. It wasn't much more than a concept, but still hade multiplayer capabilities courtesy of Orbited. Back then it looked like this:

Playgo

It fell out of grace in my busy brain while some other idea events bubbled up to my master node. But at the 16th of febraury this year, I coudn't hold it back any more - I had to have a neat project to try Titanium Mobile out, and there it was in the back of my head. I pulled it out and started prototyping straight away. I'm a hands on, iterative programmer, so I quickly got some initial results looking slightly ugly, but still promising.

Mockup

Everything in-game is pure JavaScript, HTML5 and CSS3, which made it possible to develop the game itself in Safari, and dropping it into Titanium only when it was almost done. This was crucial to keep up the speed and sanity during development. Titanium is a great piece of software, but it doesn't have very good debugging capabilities, especially not for webviews. And Safari/Chrome/Webkit Nightly have extremely good debugging tools for both logic (JavaScript) and presentation (HTML and CSS), so why not use them?

I decided to use as many tools as possible to simplify my work, which resulted in the following toolbelt:

In hindsight, I would probably have replaced jQuery with XUI or tailored code. jQuery is wonderful to use, but it's a bit heavy on mobile devices both to load and during execution. However, it does save time for the developer, so it's not a crystal clear choice. Also, make sure that you keep up with the flow of new exiting tech that might relieve your work - for example both css3please.com and cssdesk.com were release during Golingo's development.

The Construction

Most of the actual game was made in a few weeks time, but from scratch to published app it took almost six weeks of part time work. A lot of this time was spent banging my head into various walls. Again, Titanium is great, but it's a young framework with all the kinks that follows. There has been quite a few bugs, and the documentation hasn't always been up to date - but this is much better nowadays. What more - since most other developers are as clueless as yourself, It's been hard finding good resources and getting help. I did however get a trial for Appcelerator's Premium Subscription, with 48-hours guaranteed response, and I must say it's really good stuff. The developers themselves answers all your stupid questions and relieves most of the wall banging. If you can afford it, go for it!

By releasing the code for Golingo, we hope to relieve some of the headaches surrounding developing packaged HTML5 apps. I do not say that it's not full of faults, because it is, but at least it is a working example full of faults. Please don't hesitate to dig through the code to see what is going on. We believe we've solved some common problems that you too will run in to when using Titanium, for example transparently calling native functions from a webview (and vice versa) using callbacks and trickery. Here's a quick recap of that:

Connecting Titanium Contexts

Your Titanium application is built up of javascript files. There is a main file called app.js which is responsible for bootstrapping your applicaiton. As a matter of fact, you could actually put all your code in app.js, but that is only viable for very small apps. Therefore Golingo consists of lots of different files - pretty much one file per window and some util libraries. Whenever you open a webview or a window with a url pointing to a js file, they run their code in a new context - meaning you cannot easily communicate with app.js or any of your other windows or webviews. Or at least, you couldn't had the brilliant minds behind Titanium not given us app-wide events. But since they are brilliant, and they do have given us app-wide events, let's use them to let the different parts of the app communicate.

A common problem with this event-driven way of programming is that you cannot pass functions transparently back and forth between contexts since the event bridge serializes all passed data. Because of this, most people have a hard time figuring out how to call a function in another context and pass the result back to a callback specified in the calling function. We use a pattern looking something like the following, where we hijack the event firing and handling functions to hack in support for transparent callbacks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
var Test = {
    name: 'test',

    init: function(){
        this.proxiedHandleEvents = $.proxy(this.handleEvents, this);
        Ti.App.addEventListener('app', this.proxiedHandleEvents);
    },

    // Event cannon with callback fix.
    fire: function(opts){
        // If we're providing a callback, save a reference to it here
        // to be able to call it when the response returns from the other side.
        if (opts.func && opts.callback) {
            var c = ++this.callbackCounter;
            this.callbacks[c] = opts.callback;

            // Must remap the callback to a callback id since we cannot
            // pass functions between the native context and the webview context
            opts.callback = c;
        }
        opts.from = this.name;
        Ti.App.fireEvent(opts.to, opts);
    },

    // Event delegator
    handleEvents: function(e){
        // If the event object has a 'func' property,
        // and that property is a function available in our singleton - call it.
        if (typeof this[e.func] === 'function') {
            // If a callback id is provided, the caller is waiting for a response.
            // Overwrite the callback id with a replier function responding with that id.
            // When our referenced function is done, it passes its result to the replier
            // function, which makes sure the callback on the other side is passed that result.
            if (e.callback) {
                var c = e.callback,
                    self = this,
                    from = e.from;

                e.callback = function(data){
                    self.fire({
                        data: data,
                        to: from, // Return to sender
                        callback: c // Call the callback with this id on the other side
                    });
                };
            }
            if (!e.data) {
                e.data = {};
            }
            // Call the specified function
            this[e.func](e);
        }
        // Was it a callback - eg a response from the other side?
        else
            if (e.callback && this.callbacks[e.callback]) {
                // Execute the correct callback and pass it the result object
                this.callbacks[e.callback](e);
                delete this.callbacks[e.callback];
            }
    },

    checkWords: function(words){
        this.fire({
            to: 'app',
            func: 'saveHighscore',
            data: { words: words },
            callback: function(e){
                alert("We found " + e.data.correctWords.length + " correct words");
            }
        });
    }
};

Test.init();
Test.checkWords(['hi', 'ho', 'foo']);

Low Pro like a low pro

Another nice library helping the development of Golingo is Dan Webb's Low Pro. Low Pro is used to make it a breeze to attach beaviour to elements, and does it well. All our letters and boards should behave the same way, so they're all instances of the Letter and Board classes respectively. We ended up using Low Pro in a very basic way, but it does actually have support for inheritance as well as event binding and delegation. Our code should probably be rewritten to more accurately follow Low Pro and it's object oriented ways, but coding in a hurry sometimes results in less than perfect code. We'll fix that as soon as there is peace on earth. Nevertheless, I get a warm feeling from being able to just write:

1
$('<div/>').attachAndReturn(Letter, this, letter, specialLetter);

Sexifying

In Titanium, you use JavaScript to create and layout native elements and windows. This is incredibly powerful out of the box, but my feeling is that Appcelerator care more about laying the groundwork and creating the low level functions than making a sexy API. This is totally fine by me. I love that their focus means a quickly maturing API. But since I'm also all about the sexy programming, I've taken on the sexifying part. In Golingo, we started this journey by abstracting the menu creation somewhat. However, these we're only the first baby steps.

After finishing Golingo, I've been working on a few different Titanium based projects. And the more I do work with Titanium, the more I like what you can achieve, but also the less I enjoy how Titanium does it out of the box. It's way too verbose and clumsy for my liking. Also, there is no good way of separating the layouting from the element creation. Since I love HTML and CSS, I decided to do apply them to Titanium. The result is not present in the current Golingo release, but I'll talk about it in an upcoming blogpost. Here is a sneak peek of an exampe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// CSS-like styling
// test.css
tableView {
    background-color: #f00;
    color: #fff;
}
row { background-color: #0f0; }
.info { right: 0; }

// HTML-like templates combined with micro-templates or mustasche
// test.html
<tableView>
    <row>hi</row>
    <row class="red">{{test}}</row>
    <row style="background-color: blue;">
        <label class="info">info</label>
        <img src="test.png"></img>
    </row>
</tableView>

// Template data as JSON object
// test.js
{ "test": "This is sweet!" }


// Render the above files:
ui.render('test.html', 'test.js', 'test.css').appendTo(currentWin);

Even though the HTML parsing might mean too much of a overhead for big files, a better layouting mechanism is needed, but I'll elaborate on that subject in an upcoming post.

Get dirty

Dirty
I had planned to get the code in super trim and add an interactive playing guide as well as multiplayer capabilities and other goodies before releasing the source, but I realised there's not really any need to wait. If you're brave enough to wade through sometimes somewhat semi-stupid code, you should be free to do so, and not wait for our utopian dream. Maybe you could even give us a helping hand at fixing all these new fancy features. For example, it shouldn't be too hard getting most of the game to run on Android. Palm should also be within reach if you break out of Titanium or write a shim for it! I dare you!

I repeat: the code is hosted here at our brand spanking new Github account. Isn't it time for you to dive in?

Idareyou

We are very curious what you'll do with the code and all. We'll continue to develop Golingo as well as other cool apps, so stay tuned as usual. Also, we promise to catch up on the HTML5 vs Objective-C series, where we'll try to match the basic functionality of popular apps in a days worth of programming. Please feel free to leave tips for what apps you'd like to see us take on in the comments!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/395144/jacob_small.jpg http://posterous.com/users/36u9lHV4WwFz Jacob Waller Jacob Jacob Waller
Wed, 12 May 2010 11:06:00 -0700 Puzzle app step 2 - Data structure http://blog.krawaller.se/puzzle-app-step-2-data-structure http://blog.krawaller.se/puzzle-app-step-2-data-structure
Follow along as we're blogging the development of our new iPhone puzzler! In this post we define the data structures that will control the game.

We've already laid down the foundation of the project, defining the basic idea: ripping off the age-old idea of a labyrinth where the player object can travel in all cardinal directions, but always as far as possible. The why behind the adoption of this seemingly bland idea can be found in the previous post, now we're going to get started on the how!

In this post we're going to define the data structures involved. Let's start with deciding what a labyrinth data object should look like! To do that, we have to jot down our ideas of what a labyrinth can contain:

  • Of course, it has to contain some walls
  • As the screen real estate on the iPhone is rather limited, we might do well to also allow the borders between the squares to block passage.
  • We might also want special squares which somehow affect the player, for example teleporting him to a different square.
  • A neat addition to this otherwise rather stale game concept might be to have other entities in the labyrinth apart from the player object. These can be moved along with the player (and kill him upon contact), or pushed along by the player, etc.
  • One clone that I played had the concept of bonus objects, and you wouldn't get a perfect score when you reached the goal if you hadn't also collected all the loot on the level.
  • We might also want things to happen in certain conditions, perhaps allowing passage through a wall if the player has collected the key, or pressed a button no more than three moves ago, etc.

These wishes can be abstracted into the following concepts:

  • Walls, borders and entities are all of a certain type. A type has a look (class), and a flag to say if it moves with gravity or not (if it is an entity).
  • We need to have effects, affecting entities / walls / borders (changing their type, or position if an entity) or the game itself (flags, counters)
  • Then we can define what effects should happen in a collision between two types.
  • In order to spice things up we might also want to allow things to happen conditionally.

Using these concepts we can build up an object defining a level with a somewhat advanced functionality:

http://gist.github.com/386993.js?file=datastructure

With this structure, we should be able to define levels with a wide range of behaviours. Probably we'd do well to hardcode some shortcuts for the most common usecases, but this should set us off on a good start.

Now let's consider what's required to save the state of a level. What can change from the definition object?

  • We need to track the position of all entities, that will fall around the labyrinth as the player makes his moves.
  • The entities might also change type, so we need to track that as well.
  • If a wall or border has changed, we have to store that.
  • The flags and variables of the game must be kept. 
  • Finally we also need to save the number of moves.

So a save object should look something like this:

http://gist.github.com/386993.js?file=gamestate

In the first post, we mentioned the idea of a level analyzer module. It should take a level object, and then use game logic to calculate all possible states, and the transitions between them. The returned analysis object would have keys made up by serialized states. The corresponding values is an object with the states you can reach from that particular state, and what graphical transitions should be shown for this move. This analysis object will then be used for the gameplayer module, which will simply transit between the states, performing the animations. 

Here's a blueprint for such an analysis object: 

http://gist.github.com/386993.js?file=analysis

The level analyzer module building that object will look something like this:

http://gist.github.com/386993.js?file=analyzer

And here's a sketch of the gameplayer module: 

http://gist.github.com/386993.js?file=gameplayer

So the bulk of the project consists of creating these two modules! I called dibs on the analyzer, so I'll get started on that right away. Little brother, get cracking on some CSS3 magic for the gameplayer module! First one to report back here with a post about the module wins remote control control for a week!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller
Wed, 05 May 2010 09:49:00 -0700 Krawaller goes Github http://blog.krawaller.se/krawaller-goes-github http://blog.krawaller.se/krawaller-goes-github
Finally set up our Github-account, where we'll be releasing lots of front-end & smartphone-related projects. Read up here on what's already there!

Hi folks!

We just wanted to let you know that we've set up a fancy new Github accout here, to make way for our upcoming Golingo source release.

However, we'd feel a bit ashamed if it would have to stay so very reverberatingly empty until then, so we had to throw together a few projects to make it more cosy and homelike. Oh my, the priorities of a creative programmer ;)

PubSubHotTub

First out is PubSubHotTub - a lightweight pubsub broker with a lame name. However, it does have more than just a silly name - namely support for wildcard publishing and wildcard subscriptions as well as currying. It's not very well tested, apart from the test suite that ships with it, but we intend to use it in some of our upcoming projects. So we hope it will grow up to be a pretty and powerful, but still very light, tool. Here's how it looks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Demo usage of http://github.com/krawaller/PubSubHotTub

var func = function(){ console.log(Array.prototype.slice.call(arguments).join(" ")); };

pb.sub('/root/leaf/meatloaf', func, 'i', 'like', 'curry');
pb.pub('/root/leaf/meatloaf', 'and', 'cheese'); // => i like curry and cheese

pb.sub('/*/leaf/*', func);
pb.pub('/root/leaf/*', 'cheese'); // => cheese, i like curry cheese ^^ (curry cheese sounds rad)

pb.sub('/cheese/**', func);
pb.pub('/cheese/doodles/rocks', 'yeah'); // => yeah

pb.oneSub('/sausage', func);
pb.pub('/sausage', 'bratwurst'); // => bratwurst
pb.pub('/sausage', 'chorizo'); // => *nothing*

var handle = pb.sub('/goat/cheese', func);
pb.pub('/goat/*', 'cheese?'); // => cheese
pb.unSub(handle);
pb.pub('/goat/*', 'butter?'); // => *nothing*

var obj = {
    val: 42,
    method: function(){ console.log(this.val); }
};
pb.sub('/gnu', obj, 'method');
pb.pub('/gnu'); // => 42

pb.sub('/**', func, 'logger');
pb.pub('/some/random/func' 'can see dead people'); // => logger can see dead people

That's nice and easy, but still very cunning, no?

CSSMol

Second out is CSSMol - a port of the beautiful CanvasMol to use CSS 3D Transforms instead of canvas. 

Why would anyone do this, you ask? Well, we needed an excuse to play with the cutting edge CSS 3D Transforms, so why not? Mind the cutting edge-ness though - this is so new that probably only Mobile Safari, Safari 4 and Webkit Nightly supports it. But why do it then? Well, because Mobile Safari has hardware accelerated CSS Transforms - meaning we can get decent performance even on a small weak device as the iPhone.

Check out the demo on your iPhone / iPad and also add it to your homescreen, or check it out in Safari 4 or Webkit Nightly on your desktop (might only work on Mac/Linux). Sweet, hey? If you have an iPad around please let us know how it works. We're drooling all over the place after an iPad, but haven't bought one... yet :)

We might do a more detailed write up of CSS 3D Transforms and such if you're interested! Please don't hesitate to share what you would like to see from us. Very few things are impossible :)

Also, please feel free to contact us for contract work.

KTHXBYE

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/395144/jacob_small.jpg http://posterous.com/users/36u9lHV4WwFz Jacob Waller Jacob Jacob Waller
Thu, 29 Apr 2010 22:57:00 -0700 Puzzle app step 1 - The intestines of a good puzzle game http://blog.krawaller.se/the-intestines-of-a-good-puzzle-game http://blog.krawaller.se/the-intestines-of-a-good-puzzle-game
Philosophing our way to what our next application should be!

Having finally got Golingo out the door and into the app store, we’re in the process of dreaming forth our next project. While Golingo will keep us occupied for some time to come;

  • As my brother promised, he’s going to detail the creation of it in a forthcoming post, highlighting the use of web technologies and the benefits of the Titanium Framework. Start typing, Jacob! [edit: read that post here]
  • Community feedback has given more than enough ideas for an update, so Jacob is now working on a new version containing..
    • more languages (initial release has English and Swedish)
    • more game modes
    • wifi multiplayer (to complement the split-screen multiplayer already in place)
  • We’re also considering getting an Android version out, which will hopefully result in a blog post on what that transition will entail. The fact that web apps are (mostly) platform independent is one of the main arguments against using Objective C, and this conversion will put that to the test. Will it suffice to simply throw a switch in Titanium and search&replace some proprietary CSS, or is a more deep-going refactoring needed?
  • Of course we also want to keep pushing Golingo sales, trying our hand at the very strange field of internet marketing. We are completely oblivious as to what makes success there, so it’s a journey of discovery (advice much appreciated!). Golingo did however recently reach the 1000 units sold mark, meaning an wage of $2 per development hour! We just need to release 49999 more apps to get our Mediterranean beach house!

But, being developers we need to develop, so in parallel to the Golingo caretaking we’ve also started hunting down the next idea. Now, like all of you we of course have several dream projects that we’re itching to work on, projects of life-fulfilling promise but of equal complexity. Time, however, is in short supply – Jacob is in the process of securing a contract to create a travel planner application for a major Swedish infrastructure company, and I spend 80% of my time teaching mathematics & programming to the inmates of society’s penalty box. I’ve finished the Advanced JavaScript course for Linnaeus University, but still, 1 free day a week (minus household chores) doesn’t amount to much. So with the lessons from the angry carpenter fresh in memory, I realised we need to keep things simple and our heads on our shoulders.

Because of that, and because it’s also in line with a common perversion of ours, we decided to create some kind of puzzle game. They are by nature rather confined, and might therefore be doable within our limited time. I earned my programming badge in the dungeons of a beautiful MUD called Midnight Sun, where one of my favourite pastimes was making puzzles for the heroes to solve, so as to put their wit to the test and not just their character’s stats. I’m hoping I can draw on that experience to shorten development time even further.

Now, being a mathematician, I started thinking – what actually constitutes a good puzzler? Are there some mathematical traits that we need to pursue or avoid? There are some obvious answers:

  • First off, the idea needs to be both simple and clearly defined. The rules of our universe must be few and unambiguous. Take Subway Shuffle, an early iPhone favourite of mine. To play it, you only need to know that...
    • You can move all cars, but only along tracks with the same colour
    • Only one car per station at a time
    • The goal is to get your red car to the big red station.
  • You need to have a rich choice tree. Here Subway Shuffle becomes an anti-example – at any given point you only have very few options available, and more often than not the correct one is also the only one, if you eliminate backtracking.
  • There also needs to be some possibility of lookahead. If the game is completely opaque and you’re not sure how you’re doing, it’s hard to have fun. Colorbind is an excellent example of this, where it’s always possible to deduct how close you are to your goal, and whether or not you can get there from the current point. Side point: Colorbind is also really beautiful, which definitely doesn’t hurt sales nor gaming experience.
  • However, the lookahead shouldn't be too allowing. Case in point: Cross Fingers. After having stared at the board for a while and having realised how to solve a level, the actual solving is just a tedious walk through the motions.
subway shuffle colorbind cross fingers
Subway Shuffle Colorbind Cross Fingers

Having reread the above list umpteen times without managing to come up with a novel idea of our own, we eventually decided to do like all successful developers - steal one! There are innumerable basic puzzle concepts that have been reincarnated more times than Buddha, and can therefore be considered part of the public domain.

One such concept quickly rose to the top of our list of potential thieving targets: Labyrinth. At least, that's what the first reincarnation I encountered was called, which I played in the attic on my father's Macintosh more than 20 years ago. You've all experienced it in one form or other, I'm sure. Below is a screenshot from Roadblocks, a more recent (but less beautiful) flash incarnation:

Roadblocks

The idea is very simple: You have to reach the goal. You're able to travel in any cardinal direction, but cannot stop mid-flight. In a way, you could say you're controlling gravity - whenever you press an arrow key (or tilt the iPhone, perhaps?) in a certain direction, the player object will travel as far as possible in that direction.

And, that's pretty much it! I think the simplicity explains the longevity of this seemingly bland concept. The labyrinth will always be much smaller than it seems, since only a few positions are actually reachable. To make things more interesting and to increase the branches on the choice tree, various spices are usually added: teleports, breaking blocks, etc. So while the basic concept is simple enough to implement, there seems to be ample opportinuty to breathe some fresh air into it all by thinking up new ways to spice things up!

Having finally decided on what to aim for, I sat down to make a sketch of the project. First I jotted down some basic thoughts & premises:

  • We will of course follow the path Golingo cleared, and program this game using only web technologies. Probably we'll pack it up in Titanium, but we don't need to make that decision until way further down the path.
  • To allow for lots of exotic spices, I want to make an abstract, flexible game engine that can easily incorporate the new ideas which will inevitably pop up along the line (movable blocks! enemies! multiple player objects! levers! inventory! delayed effects! etc etc ad infinitum).
  • Will Wright has many claims to fame, but for me the most important lesson he taught is that of the humongous size of peoples' pride. How come The Sims, a game by definition utterly boring (your characters use the toilet, for Christ's sake), has had such a remarkable success? It is based on user generated content, that's why! Incorporating a level editor into our game would be a neat way to capitalise on that, as well as making it easier for us to create the levels to be packaged with the game.
  • Since we're short on both time and graphics skill, we'll use our otherwise unhealthy fascination of new web tech to give the game a simple but hopefully stylish look using mostly (only?) CSS.
  • I also want the game to feel at home on the iPhone. Colorbind is again a prime example, using the touchscreen and gimmicks (shake the phone to clear what you've done) to great effect. Contrast this to Puzzle Quest, which was ported straight to the platform without any regards as to what makes it special, leaving the game feeling rather alien to play.

A further brainstorming session in front of this list gave birth to the idea of the Analyzer. If we are to allow players to make levels of their own, they need to have some tools to make sure that their level is actually solvable. So why not put all game logic into this tool? I'm going to make a module that analyzes a given level, and spits out a data object containing all possible board positions, and the connections between them. That allows us not just to check the integrity of a level, but also to sort them difficultywise programmatically. 

The gaming module will therefore not contain any game logic at all, but just perform the animations when transitioning from one state to another, and keep track of the current state. This should allow for a very neat separation of concerns in the codebase.

It also makes the whole project split neatly down the middle, meaning me and my brother can wrestle with one half each! I already have most of the Analyzer code written down in my head (I have an editor in my brain, but unfortunately it can't yet run any code), so I'm going to call dibs on that. Which will suit Jacob fine, as he's quite skilled in the CSS graphics department anyway - he made Golingo using almost no actual pictures, save the wooden background. 

So that's where we're at now! I'm in the process of writing some specs of the data objects to be passed around, but when that's done we can both get to work individually, without depending on the progress of one another. Time (and a follow-up post) will tell how it all turns out!

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/396648/me.png http://posterous.com/users/3syhoGuvQUOl David Waller David David Waller