Appliness #8 – November 2012

89
Picture by Elle Osmani

Transcript of Appliness #8 – November 2012

Page 1: Appliness #8 – November 2012

Pic

ture

by

Elle

Osm

ani

Page 2: Appliness #8 – November 2012

appliness(THE FIRST DIGITAL MAGAZINE FOR WEB APPLICATION DEVELOPERS

WELCOME TO APPLINESS. THE CONTRIBUTORS OF THIS FREE MAGAZINE ARE ALL PROFESSIONAL AND PAS-SIONATE DEVELOPERS. IF YOU WANT TO WRITE A TUTORIAL, SHOWCASE YOUR APPLICATION, CONTACT US ON OUR WEBSITE APPLINESS.COM. WE HOPE THAT YOU ENJOY READING THE 8TH ISSUE OF THIS MAGAZINE.

TABLE OF CONTENTS

NEWS ABOUT HTML AND JAVASCRIPTby Brian Rinaldi

HELTER SKELTER NEWS

NAVIGATION GUIDEREAD NAVIGATE

MOVE TO THE NEXT ARTICLE BY A HORIZONTAL SWIPE

READ THROUGH THE ARTICLE BY A VERTICAL SWIPE

GO BACK TO THE LIBRARY

MOVE TO THE PREVIOUSARTICLE

DISPLAY THE TABLE OF CONTENTS

VISUALLY BROWSE ALL THE ARTICLES

TUTORIALS

8 TIPS FOR ANGULAR.JS BEGINNERSby Sudhanshu Raheja

JAVASCRIPT: OPERATORSby Dmitry Baranovskiy

DELAY INITIALIZATION WITH JQUERY DELEGATIONby Joe Zimmerman

APPLE PUSH NOTIFICATIONS WITH PHONEGAP by Holly Schinsky

DOES JAVASCRIPT NEED CLASSES?by Nicholas Zakas

NODE.JS, REQUIRE AND EXPORTS by Karl Seguin

INTERVIEW

ADDY OSMANI - THE MODERN YEOMAN

Exclusive interview by Maile Valentine

EMBRACE THE STATIC WEB WITH PUNCHby Lakshan Perera

SHOWCASE

COMPLETUREbuilt with PhoneGap

NATIVE SCROLLING IN JQUERY MOBILE/PHONEGAP APPLICATIONS by Piotr Walczyszyn

NODE.JS, MODULE.EXPORTS AND ORGANIZING EXPRESS.JS ROUTES by Karl Seguin

PHONEGAP, APPLE REJECTIONS & UI/UX GUIDELINES by Andrew Trice

LIBRARY OF THE MONTH

INTERVIEW

JEREMIE PATONNIER - CSS & SVG EXPERT

Exclusive interview by Vincent Hardy

INTERVIEW

PAUL D. HUNT - FONT DESIGNER Exclusive interview by Michaël Chaize

WHY ARE PREPROCESSORS SO DIVISE? by Kianosh Pourian

HACKING JAVASCRIPT’S FORMAT PARAMETERS WITH FUNCTION.APPLY() by Jeremy Kahn

USING YEOMAN WITH ANGULAR.JSby Brian Ford

CHEAT SHEET

5 HTML5 APIS YOU DIDN4T KNOW EXISTEDby David Walsh

Page 3: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Sudhanshu Raheja

8 TIPS FOR ANGULAR.JS BEGINNERSWE STARTED WORKING WITH ANGULAR.JS RECENTLY AND, AFTER SPENDING A FEW DAYS ON IT, I RE-ALISED THAT THERE WAS A BIG NEED FOR BEGINNER TUTORIALS ON IT. I’VE TRIED TO DOCUMENT SOME OF THE THINGS YOU MIGHT NEED ON DAY 1.

#1 Yes, it’s really worth it. So do spend a little extra time.

Here’s an example of the issues you would face:

Discussion from StackOverflow: http://stackoverflow.com/questions/10486769/cannot-get-to-rootscope

Thanks, it makes perfect sense, but how did you know that? Was it in the docs? – Malvolio May 7 at 21:55

@Mavolio No, he is one the 3 core developers. – ChrisOdney Jun 6 at 19:36

The documentation sucks and you have to assume stuff. But there is light at the end of the tunnel.

If you need resources, you should try out the following:

a. Run through the videos first – this should get your hooked. The fol-lowing two are essential

- http://www.youtube.com/watch?v=WuiHuZq_cg4

THE DOCUMENTATION STILL SUCKS SO IT’S OKAY IF YOU’RE TAKING MORE TIME.

Page 4: Appliness #8 – November 2012

- http://www.youtube.com/watch?v=IRelx4-ISbs

b. Run through the tutorial – http://docs.angularjs.org/tutorial/step_00

c. Run through the concepts – http://docs.angularjs.org/guide

d. Finally, keep this open – http://docs.angularjs.org/api/ – it won’t help much other than just to remember what some function did.

e. Read this blog post – http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UP-DATED

f. If it did look interesting, add AngularUI to your project – https://github.com/angular-ui/angular-ui/

g. Go and join the AngularJS google group. It’s quite active.

#2I have divided the code into two files. The first is the app.js and the second is the controllers.

App.js contains code for setting up routes, app.factory functions and app.run to setup $root-Scope. Controllers.js contains all controllers so far.

#3I do this in the App.js file:

var app = angular.module(‘beta’, [], function($routeProvider, $locationProvider) { $routeProvider.when(‘/home’, { templateUrl: ‘/partials/home’, controller: HomeController }); // When you put /home, it also automatically handles /home/ as well $routeProvider.when(‘/login’, { templateUrl: ‘/partials/login’, controller: LoginController }); $routeProvider.otherwise( { redirectTo: ‘/login’} ); // configure html5 to get links working // If you don’t do this, you URLs will be base.com/#/home rather than base.com/home $locationProvider.html5Mode(true);});

HOW TO DIVIDE CODE

HOW TO INITIALIZE THE APP

2/5

Page 5: Appliness #8 – November 2012

#4 This is, again, done in the app.js file.

app.factory(‘db’, function() { var items = []; var modify = {}; var modify.addItem = function(item) { items.push(item); return ‘added item’; }; var modify.getItems = function() { return items; } return modify; // returning this is very important});

now, in your controller, you can access these as follows:

function MainCtrl = function ($scope, db) { $scope.save = function() { db.addItem(‘hello’); console.log( db.getItems() ); };}

#5 This might seem a little stupid for people who have been doing this for a long time, but, well I stumbled on this, so this makes the cut.

Basically, what this means is that whenever you’re trying to test your controller to try out something new, don’t try this:

function MainCtrl = function($scope, db) { db.addItem(‘hello’);}

This won’t work for obvious reasons. What you need to do is this:

function MainCtrl = function($scope, db) { $scope.save = function() { console.log( db.addItem(‘hello’) ); }}

CREATE A SET OF FUNCTIONS THAT YOU CAN USE

CONTROLLERS ARE JUST FOR DEFINING THINGS

3/5

Page 6: Appliness #8 – November 2012

and now to run the save function, go to JADE and add:

input(type=’submit’, name=’submit’, value=’Submit’, ng-click=’save()’)

Now open the form, click on submit and check out console.log.

#6The $rootScope is a global, which means that anything you add here, automatically becomes available in $scope in all controller. Nice eh!

To set it up, you need to do something like this (I do it in app.js):

app.run(function($rootScope) { $rootScope.hello = function() { console.log(‘hello’); }});

This should now be available in controllers:

function MainCtrl = function($scope) { $scope.save = function() { $scope.hello(); }};

#7To use the validation which comes by default with Angular, you need to follow the following steps:

a. give a “name” to your form e.g. <form name=”loginForm”>

b. mark all required input boxes as required e.g. <input type=’email’ required />

c. to turn on say email validation, you need to set type=’email’

d. check if the form is validating or not by checking loginForm.$invalid. To check this inside your controller, do $scope.loginForm.$invalid

DEFINE FUNCTIONS IN THE $ROOTSCOPE

FORM VALIDATION

4/5

Page 7: Appliness #8 – November 2012

ABOUT THIS ARTICLE

Sudhanshu Raheja is an entrepreneur based out of Pune, India. He founded Vercingetorix Technologies (http://vxtindia.com), a consulting firm which part-ners with brands to define and execute their mobile strategy. http://vxtindia.com/

@sudhanshuraheja

Angular JShttp://angularjs.org/

Vercingetorix Technologies on Facebookhttps://www.facebook.com/vercingetorixtechnologies

Vercingetorix Technologies’ Portfoliohttp://vxtindia.com/portfolio

ONLINE RESOURCES

#8If you have defined ng-app in the HTML tag, and have defined an ng-view in the body somewhere. How-ever, you want to keep the menu outside ng-view and still want to have access to it programatically to change menu based the fact that the user is logged in or not, you can define a ng-controller on the menu and make it work like a normal controller.

Another thing I did was to put my menu in $rootScope so that each controller can mark which menu should be used and which one is active.

HANDLING THE MENU VIA NG-CONTROLLER

Page 8: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Dmitry Baranovskiy

JAVASCRIPT: OPERATORSIN THE PREVIOUS ARTICLE I TALKED ABOUT TYPES AND TYPE COERCION IN JAVASCRIPT. IN THIS ONE I WANT TO TALK MORE ABOUT HOW THIS COERCION APPLIES TO JAVASCRIPT OPERATORS. LETS GO OVER SIX MAJOR OPERATORS AND LOOK AT HOW THEY WORK.

TYPEOF

The typeof operator returns a string representation of the type of the passed expression. There are two major points to note:

•Unresolvable references will produce “undefined”, i.e. typeof a will return “undefined” if vari-able a was not declared.

•typeof lies in two cases for null and for function () {}.

Apart from this, operator works pretty much as a lookup table:

Type of expression Result

Undefined “undefined”

Null “object”*

Boolean “boolean”

Number “number”

String “string”

Object, that can’t be invoked “object”

Object, that can be invoked “function”*

Page 9: Appliness #8 – November 2012

I marked with “*” two places where operator is misleading: type of null is Null and the actual type of any function is Object.

SUBTRACTION

Converts both arguments to number. “8” - true is converted to 8 - 1. Very simple, indeed. Don’t expect the same from addition :)

ADDITION

Addition is one of the trickiest operators in JavaScript. Lets see what is going on when you write a + b:

1. Both arguments are converted to primitives. Lets call them A and B.

2. If any of primitives is a String, concatenate A and B as strings.

3. Otherwise compare A and B as numbers.

For example:

//EXAMPLE8 > “5” :: 8 > 5 :: true;8 > true :: 8 > 1 :: true;“8” > “18” :: true;

LESS THAN

In contrast to the addition operator, the less-than operator compares arguments as strings only if both of them are strings. To put it more formally, here are the steps:

1. Both arguments are converted to primitives. Lets call them A and B.

2. If both of primitives are Strings, compare A and B as strings.

3. Otherwise compare A and B as numbers.

For example:

8 > “5” :: 8 > 5 :: true;8 > true :: 8 > 1 :: true;“8” > “18” :: true;

2/3

Page 10: Appliness #8 – November 2012

STRICT EQUALS

The favourite operator of many, also known as triple equal (===) does things in a very simple way: checks if the arguments are of the same type and if they are, checks if they are equal. His little brother has a little bit more complicated character.

EQUALS

Ok, here it comes, the most hated operator of the language. According to the spec it works like so:

1. First check for types, if they are the same, apply strict equals.

2. If both arguments are either null or undefined, return true.

3. If one of them is String and the other is Number, convert both to Number and apply strict equals.

4. If one of them is Boolean, convert it to Number and go to 1.

5. If one of them is String or Number and the other one is Object, convert object into primitive and go to 1.

6. Return false.

This basically means that equals works like less-than, when the types of the arguments are different and like strict equals, when types are the same. The easy way to remember: when the types are different it converts both arguments into primitives, then into numbers, unless they both are strings. Oh, and null == undefined is true.

8 == “5” :: 8 == 5 :: false;1 == true :: 1 == 1 :: true;

0 == “” :: 0 == 0 :: true;0 == “0” :: 0 == 0 :: true;“” == “0” :: false;

“1000” == “1e3” :: false;1000 == “1e3” :: true;5 == {valueOf: function () { return 5; }} :: 5 == 5 :: true;

These are not all the operators, but certainly the most tricky ones.

Page 11: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Joe Zimmerman

DELAY INITIALIZATION WITH JQUERY DELEGATIONAS THE INTERNET FILLS WITH MORE AND MORE JAVASCRIPT CODE, WE NEED TO BECOME MORE AND MORE AWARE OF THE IMPACT OF OUR CODE HAS ON PERFORMANCE. ONE OF THE BIG PAIN POINTS CAN COME FROM ALL OF YOUR CODE BEING INITIALIZED AND LOADED DURING JQUERY.READY() OR (IF YOU’RE A GOOD BOY WHO PUTS ALL THE CODE AT THE END OF THE DOCUMENT) RIGHT AWAY. WE CAN DELAY SOME INITIALIZATION UNTIL LATER, RIGHT?

EVENT DELEGATION

For a while now, jQuery has had event delegation. If you know what event delega-tion is and how it works, go ahead and skip to the next section. But, for those of you who don’t know, here’s a little introductory course.

Normally you would attach an event listener directly to an element, and let the han-dler go from there. Generally there is absolutely nothing wrong with this, but if the elements that you wish to attach event listeners to are dynamic (they’re constantly being created and/or deleted), this can be a hassle. Another time this can be “bad” is when there are many, many elements to attach to, in which case it’s just slow.

Event delegation was designed for these situations.

The premise behind event delegation is pretty much the opposite of real-world delegation. Rather than delegating things to those below us, we del-egate to elements higher in the hierarchy. Sometimes we even delegate all the way up to the CEO (document). Let’s take a look at a tiny code sample and walk through it to explain.

Page 12: Appliness #8 – November 2012

// Normal$(‘.elements’).on(‘click’, function() { // Do Something}); // Delegation$(document).on(‘click’, ‘.elements’, function() { // Do Something});

With delegation, we attach the listener to an element higher in the hierarchy (document in this case). Then we add another argument to the call to on that specifies a selector that we need to match. Other than that, it’s exactly the same as the normal event listener.

Here’s how it works:

1. The document listens for click events. Any click that happens on the page will bubble up to the document (unless it was stopped by another event handler).

2. When the document hears a click event it checks to see if the event happened on an element that matches the selector we passed in (‘.elements’ in this case).

3. If it matches, it fires the event handler.

It’s that simple. One of the best parts is that the document is created immediately, so you can attach listeners to it within the head of the document and these will still work. If you want to learn more about event delegation, look here.

DELAYED INITIALIZATION

Many times the delayed initialization works pretty well when working with jQuery plugins. The best way I can explain this concept is through examples. I’ll show two examples of initializing plugins that demon-strate a few of the possible hitches you may run into and how to work with them.

THE LIGHTBOX

This first example utilizes the jQuery lightBox plugin, which may not be the best plugin, but it works for my example. This plugin attaches itself to links to images, and then when you click on the link, instead of just following the link, it creates a modal box with the image contained inside it. If you are using this with a large gallery or you are using infinite scrolling to load more images in dynamically, the normal initializa-tion might not be the best bet for you.

2/5

Page 13: Appliness #8 – November 2012

Try this:

We delegate a click event listener on the document to limit the amount of code that runs right away. This delegation makes sure we don’t set the plugin up until we need it and only on the elements that need it at the moment. So, when a gallery link is clicked, we initialize the lightbox plugin on that one link. We need to trigger a new click event on it right away so that lightbox will respond to the click. Then we need to prevent the default action so that we don’t follow the link to a different page. The nice thing about the lightbox plugin for this example is that it automatically prevents bubbling, so once the lightbox plugin is initialized on a link, this delegated event handler will never run for that link again. If we weren’t using JSFiddle, you’d see that ‘init’ is only logged the first time that you click an image.

This technique has some pros and cons.

Pros:

•Really low amount of initial overhead computation.

•We don’t need to wait for DOM ready to set up the event listeners

•Initialize only the elements you need when you need it.

•Works for dynamically added content without any additional work.

Cons:

•The lightbox must be set up when you click, so there could be a delay between the click and the reac-tion to the click. This is generally unnoticeable.

•There may be other things that prevent the delegation from reaching the document and there is a bit of overhead associated with bubbling all the way up to the document.

•A wee bit more code to write. 3/5

Page 14: Appliness #8 – November 2012

THE DATE PICKER

This example uses jQuery UI’s Date Picker Widget. It was also taken directly from Elijah Manor’s post, which was the inspiration of this post. We handle things slightly differently this time.

You’ll notice a few distinct differences in implementation between this example and the lightBox example.

1. We use “:not(.hasDatePicker)” in the selector. Date Picker assigns this class to an element that the widget has already been initialized on, so we can use that to make sure we don’t initialize the Date Picker on an element that it has already been initialized on. This is nice because the Date Picker doesn’t prevent bubbling like the lightBox did, so we need some other way to know not to initialize the element. What’s also nice is that we can use this inefficient selector because it isn’t scanning the document for this selector, it’s only comparing the element we have to the selector.

2. We’re using a toastr library instead of console so you can actually see when it’s initialized and not ini-tialized. This of course, doesn’t really matter in real apps.

3. We don’t need to trigger a focus event again. The Date Picker is smart enough to know that it should show because its input is in focus already.

4. We don’t need to prevent the default action. This is because nothing happens by default when some-thing is focused.

4/5

Page 15: Appliness #8 – November 2012

ABOUT THIS ARTICLE

Joe Zimmerman has been doing web develop-ment for 12 years, which may make him sound old, but since he started in middle school, he’s still pretty young. HTML and CSS were the cool-est inventions ever. In college he was introduced to real JavaScript, starting his full addiction. Now his addiction pushes him to continuously learn more and spread the knowledge to the internet. http://www.joezimjs.com/

@JoeZimJS

jQueryhttp://jquery.com/

jQuery Lightbox Pluginhttp://leandrovieira.com/projects/jquery/lightbox/

jQuery Datepickerhttp://jqueryui.com/datepicker/

ONLINE RESOURCES

PREVENTING RE-INITIALIZATION

That first point above is one of the key points that you’ll have to think about each time you attempt to delay initialization like this. You have to find a way to make sure that the initialization doesn’t happen mul-tiple times. In the first example, lightBox’s prevention of bubbling did that for us. With the Date Picker, we had to check for a class that it adds. For other plugins, you may have to wrap the whole event handler in an if statement that checks for the initialization state somehow. Some plugins do this themselves, so you can call the initializer all you want and it won’t matter, but I wouldn’t count on it unless you read through the code yourself.

CONCLUSION

Overall, it’s pretty simple to delay initialization of many jQuery plugins and other JavaScript code. In fact, just converting to delegation for many of your event listeners prevents a lot of overhead and initialization code from running. Go out and make your JavaScript faster today! God bless and happy coding.

Page 16: Appliness #8 – November 2012

J E R E M I E PATONNIERCSS & SVG EXPERT

EXCLUSIV

E INTERVIE

W

© Guy Lerat

1/5

Page 17: Appliness #8 – November 2012

HELLO JÉRÉMIE. CAN YOU TELL US WHO YOU ARE, WHAT YOU DO AND WHY YOU ATTENDED “THE GRAPHICAL WEB” CONFERENCE? WHAT’S YOU FAVORITE WORKING ENVIRONMENT?

Hello, my name is Jérémie Patonnier. I’m a web consultant specialized in front-end design and development for the French web company named Clever Age. I attended “The Graphical Web” conference to have the opportunity to meet the people working on the next generation of graphical web technologies.

My working environnement is made of 4 parts : A MacBook Pro (which is amazingly comfy but with the power of a UNIX bash when it’s necessary), Firefox as my primary web browser (for development as well as for casual browsing), A good text editor (Sublime Text 2 right now, but I change quite often) and the Adobe CS Suite for all my graphical work (mainly Photoshop and Illustrator).

WITH BOTH YOUR SVG AND CSS HATS ON, WHAT DO YOU THINK OF THE CURRENT CONVERGENCE BETWEEN THE TWO LANGUAGES ABOUT FILTERS, EFFECTS, ETC?

I’m very pleased to see that SVG and CSS features are converging. It’s very exciting to see some SVG specific features moving to CSS because it means it will be soon possible to use them with HTML. Transformation where the first move and we can see how eager the web designers and developers are to use it. Filters, Masking, Clipping, etc... are coming as well into CSS and I wish things were moving faster. However, it’s already very fast and it requires time to learn all of this. On the other side of the technology, I’m also very pleased to see all the power of CSS Text & Fonts coming to SVG as well as an harmonization of the syntax of both languages in favor of CSS.

ARE CSS AND SVG CONVERGING ENOUGH?

I think so. Even if there is still some important gap such as CSS Animations vs SVG Animations, it’s moving the right way. As an “old” web author, I remember back in 2000 when we get stuck with almost only one browser. In comparison, today things are moving fast and smooth on many points. Of course, nothing is perfect and some people would see things moving faster but as I say, I thinks it’s moving the right way. By “the right way” I mean : technologies evolved in a very author friendly way and browsers implement things fast, allowing us to deliver some very impressive web sites (and apps) to the end users.

SVG IS STILL RARE IN TOP400 WEB SITES, WHAT’S MISSING?

Well, I think SVG has suffered from two big problems: first, in its early days SVG was not very well supported among browsers and at the same time Flash has evolved very quickly pushing SVG in the shadow. Even if things are changing, IE8 is still a problem to a wider adoption of SVG. Second, very few designers had used SVG so there is very few SVG “eye candy” image out there. As a consequence many designers think of SVG as a “technical” image format. This perception increased when, a few years ago, Adobe acquired Macromedia and drop active support on SVG in favor of Flash... but it seams the wind is changing now. It is

2/5

Page 18: Appliness #8 – November 2012

worth noticing that the uprising of the Raphael library has helped a lot in the revival of SVG and we start to see more and more SVG in modern Web design. Now, if we want to see more SVG in the top400 web sites, I think it’s missing only 2 things : good documentation (Mozilla as well as the W3C are working on this) and some aggressive evangelism about this technology and the way it can be mixed with other web technologies.

HOW DO YOU USE CSS TODAY? WHAT IS THE MOST IMPORTANT OR MORE USEFUL PART OF CSS FOR YOUR ACTIVITY?

Today, I’m using CSS without thinking about it. It’s now common practice for me and my company to use CSS to design web sites as well as web apps. Our core use of CSS is arround layout where we are actively using grid systems (we built our own based on the blueprint framework and we are currently switching to a new grid system built on top of Compass). We also make an extend use of the text and font abilities (http://typographisme.net) as well as Media Queries.

© CheekFille

3/5

Page 19: Appliness #8 – November 2012

OUTSIDE OF YOUR “PRO” ACTIVITY, WHAT CURRENT CSS CAPABILITY ARE YOU PERSONALLY MOST ENTHUSED ABOUT USING?

In my opinion, the best is yet to come. I’m eager to see all the new layout capacity because it will help to solve hard problems we all face every day. But once this is done, I’m higly excited by 3 new spec proposal : CSS Exclusions, CSS Filters and CSS Compositing and Blending.

I come from the print industry so I dream of what CSS Exclusions bring for years. Having a text flowing around a shape opens so much graphical oportunity for web designers! Filters are also a power house, especially custom filters based on shaders that will allow to bend any HTML element. Combined with the Compositing and blending proposal it just blows my mind, it’s like having the power of Photoshop in real time in my browser!

HOW DO YOU THINK THE CSS WORKING GROUP IS ADRESSING COMPLEX LAYOUTS WITH ITS CURRENT LAYOUT PROPOSALS (FLEXBOX, GRIDS, REGIONS, EXCLUSIONS, ETC.)? WHAT ELSE DO YOU NEED IN YOUR PRODUCTION WORK?

The combination of Flexbox, Grids and Regions allows to solve all common problems we have with layout. More important, those three tools will allow web developer to do something they expect since the early days of CSS 2.0: being able to build layout independent from the HTML flow order. Once the layout problems will be solved, the next big step in our production work will be all the special effects. This includes animations (that must be rationalized), control over the visual text flow (as I said previously, I have dreamed of exclusion shapes for years) and all type of filters (basic filters but also blending, compositing, clipping and masking).

There are also some needs on the JS part such as a convinient way to use SVG in Canvas and vice versa and to properly mix audio and video with SVG.

WHAT IS THE MOST DIFFICULT DESIGN PROBLEM WITH YOUR CURRENT WEB PLATFORM WORK? HOW DO YOU SOLVE IT? POLYFILLS?

The biggest issue I face is interoperability... on all technologies. Most of the time, I handle HTML/CSS issue by using the “progressive enhancement” and “graceful degradation” principle. SVG and JS are a bit more tricky and I usually rely on common framework such as Raphael and jQuery. Finally, I only use polyfills for cutting edge technologies. For example if I want to use browsers DB, I use a polyfill to mimic indexedDB on platforms that support only legacy Web SQL. By the way, CSS vendor prefix is a no brainer for me. I make an extensive use of CSS preprocessor (LESS or SASS) to completely avoid this problem.

MORE GENERALLY, WHAT DO YOU EXPECT FROM THE FUTURE OF CSS?

As the browsers become more and more powerfull, CSS can reach some new places unreachable a few years ago. For example, there is still big discussion about selectors and the opportunity to select parent node from a given node. CSS variables are also

4/5

Page 20: Appliness #8 – November 2012

something really interesting to solve some maintenance issues for web developers. In a more prospective way, I wish for a better text line break algorithm in order to have nicer text rendering. Advanced visual effects are also something really appealing. The big challenge in the upcoming year for CSS will be to find a way to bring all of this to authors (developer and designer) in a way that remain as easy as it is today to use CSS. To achieve that, I urge web designers and web developers to get involved with browser vendors, through W3C or through events like “The Graphical Web” or “Test The Web Forward”. It’s good for web developers because it allows them to better understand what’s at stake under the hood and it’s good for browser vendors because they desperately need feedback “from the battle field”. The future is full of promises and I look forward to it.

YOU ATTENDED TEST THE WEB FORWARD IN PARIS? WHAT DO YOU THINK OF IT? ARE WEB STANDARDS INTEROPERABLE ENOUGH?

Yes, I was there. This is a great event that is really helpfull for everyone who want to be involved in building a better Web. Interoperability is the biggest issue on the Web and is the main source of problems when someone is building a Web site. Writing tests that will be used by browser vendors to make sure their browsers work as we expect them to is awesome. It’s maybe the easiest way for web developers to make a big difference in the future of the Web. This is a direct contribution to the standardization effort and it’s also a way to better understand the interoperability issues of web technologies.

ANYTHING YOU WANT TO ADD?

Just a last word to spread about my main commitment to the open web technologies. Those technologies become more and more complex so it’s really important to have good documentation about those technologies. This documentation is necessary for beginner as well as for experienced developers. If you find a useful technique, if you find clever workaround, if you find a way to make clearer the way a property, an attribute or a tag works, for example, please share it. At least write it on your blog but if you want to be part of a bigger effort, feel free to contribute to initiative as MDN (http://developer.mozilla.org) or Dev.Opera (http://dev.opera.com). The W3C is also working on that topic and you should heard more about this in a few weeks. Your help will always be welcome :)

5/5

Page 21: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Holly Schinsky

APPLE PUSH NOTIFICATIONS WITH PHONEGAPTHIS IS PART 1 OF A NEW SERIES TO HELP EXPLAIN HOW TO SET UP AND USE APPLE PUSH NOTIFICA-TIONS (APNS) IN YOUR MOBILE APPLICATIONS.

APPLE PUSH NOTIFICATIONS

Push notifications are different than local notifications in that they are coming from a 3rd party server to inform the user of something, versus a local notification which is scheduled by the application to run on the device itself without any server interaction. For instance you may receive a push notification from Facebook notifying you that someone has added you as a friend, or if you are a Words With Friends player you may receive a push notification indicating it’s your turn. An example of a local notification would be an alert popping up at a certain time or interval as a reminder from a to do application where you set a date/time to a task and the alert pops up to remind you at that specified time. To the end user they may appear the same in that they both pop alerts, can have sounds associated etc, but they are very different from a development perspective.

There are Cordova/PhoneGap plugins to do both local and push notifications for iOS, but this series will focus on push notifications. If you’re wondering about Android, there is a concept of push notifications but the setup and process is a bit different and will be covered in a later post.

The process to get started with setting up APNs can be a bit intimidating initially but it’s worth taking the time to do so as the use cases are endless. This series is intended to help you understand the whole process including setup and what is occurring on both the application and server-side with sample code to get you started quickly..

Page 22: Appliness #8 – November 2012

APN WORKFLOW OVERVIEW

EXPLANATION OF WORKFLOW

Upon launch, your application communicates with the Apple Push Notification Service to authorize it to receive push notifications.

Apple responds with a unique token that must be used in all future communications to receive push no-tifications.

Your application sends that token to a 3rd party server (your own or some other provider like Urban Air-ship for instance), that will store it for later events when the application needs to be notified.

When an event occurs where your application needs to receive a notification, the server script reads in the unique device token and sends a message with a pre-defined structure to the Apple Push Notifica-tion Services which then securely sends to your device. The structure may include a message, sound and badge number to display on the application launch icon or any combination of the three.

HIGH LEVEL HOW-TO (DETAILS TO FOLLOW):

1. iOS Provisioning Portal

Create a new App ID with push notifications enabled and an SSL Certificate associated

Create a new provisioning file for the above App ID and download it

Drag new provisioning file into XCode (or via XCode Organizer)

Associate new provisioning file with your Project in the Code Signing Options

2. Cordova/PhoneGap Plugin Setup

Download Cordova Plugin for PushNotifications

2/12

Page 23: Appliness #8 – November 2012

Add PushNotification plugin key and value to Cordova.plist

Drag PushNotification folder to XCode Plugins Folder (create groups for any added folders) – only the PushNotification.m and PushNotification.h are needed here for the native, see next step for the Push-Notification.js client side

In Finder, copy the PushNotification.js file from your downloaded plugin into the existing www folder

Add a script tag to refer to the new PushNotification.js

Add methods to the AppDelegate.m (under Classes) to handle push notification events and code for handling launch of application from a push notification

3. Client Side Application Handling

Add code to register the user’s device

Add code to listen for notification events when app is active

Add code for badge management (clear on relaunch from notification etc)

Add code to check user’s notification status – which options do they have set for this application spe-cifically (they can control notification type, badge/alert/sound)

Add code to get pending notifications (ie: if app is opened from the push notification, we need to ac-cess that notification to get the data passed in to see if updates are needed etc)

Include resources in your project for custom sounds or launch images to be associated with your push notification

4. Server Side Handling (Optional)

Specify the URL to the Apple Push Notification Service gateway (sandbox or production)

Ensure proper certificates available on server

Specify any custom sounds

Special any launch images

Save registered device id’s in a database

SSL CERTIFICATES AND PROVISIONING

The first thing you need to do is set up certificates and provisioning to provide a secure connection for communication between servers and your application. Don’t let this step scare you, it’s not that bad once you do it . There’s a great article here that documents this process with screenshots and details that you should use for this step. In the next paragraph I attempt to put words to exactly what it is you’re doing and why for those that want to understand better, but feel free to skip that paragraph if you just want to go through the setup using the article.

Certificates and Provisioning Explanation

Basically your application needs to be enabled for push notifications through the Apple iOS Provisioning Por-tal via an App ID (com.mysite.myapp) and signed with a provisioning profile that includes this push enabled application identifier. The App ID also needs to be associated with an SSL certificate for communicating se-curely with Apple’s Push Notification Server. When you configure the App ID through the portal, a wizard will prompt you to create an SSL certificate that will be associated with your App ID and used for that purpose. Having the association with the App ID will will ensure the notifications sent from your server to Apple’s APN Server will then be sent to *just* the application with that matching id. Once the certificate process is com-plete you will need to download a new provisioning file for this new App ID containing the enabled push notifications. You then drag it into XCode and make sure it is the provisioning profile that is selected for your 3/

12

Page 24: Appliness #8 – November 2012

application in the Code Signing screen (under Build Settings for your project).

SETTING UP YOUR APPLICATION

Now that you’re ready to start coding your HTML/JavaScript/PhoneGap application, go through the following steps to set it up:

1. Get the latest PhoneGap Push Notifications plugin from GitHub.

2. Drag and drop the PushNotification folder to the Plugins folder in XCode and select the “Create groups for any added folders” as the copy option as shown in the screenshot.

3. Go out of XCode and into Finder and copy the PushNotification.js file into your www folder (or in a subfolder called plugins underneath the www folder to keep it cleaner). It will automatically show up in XCode for you. You cannot drag a file into XCode into this folder because of the way that it’s set up as a folder reference (icon is blue). See the sample project for further reference.

4. Add a script tag to refer to the PushNotification.js file in your HTML file such as:

//INSERT THIS LINE OF CODE<script src=”js/PushNotification.js”></script>

5. Add the plugin key and value to your Cordova.plist (found under your project root Resources fold-er)

4/12

Page 25: Appliness #8 – November 2012

The Cordova PushNotification plugin gives you a nice JavaScript API you can use from your HTML/JS files to interact with the underlying native code for handling the registration and receiving of push notifica-tions. Some of the functions provided are listed here:

- registerDevice()

- setApplicationIconBadgeNumber()

- getRemoteNotificationStatus()

- getPendingNotifications()

To use it though, you first need to add some things to the native application code to bridge to the specific push notification code. The AppDelegate class for an application (located under your project Classes folder) implements the handlers for application-wide events, such as application launch, termi-nation and more. There are also events available for handling notifications. A list of them can be found here in the Handling Notifications reference. These methods are not implemented by default though, so in order to support them we need to add the code handlers and have them delegate to our included PushNotification.m class in our plugin code. The code to add is shown in the README for the plugin but I’ll paste it here as well for further reference. You’re basically handling three events with it:

- didReceiveRemoteNotification

- didRegisterForRemoteNotificationsWithDeviceToken

- didFailToRegisterForRemoteNotificationsWithError

Add the following code block to your AppDelegate.m class before the @end to handle the notification events:

/* START BLOCK */#pragma PushNotification delegation - (void)application:(UIApplication*)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{ PushNotification* pushHandler = [self.viewController getCommandInstance:@”PushNotification”]; [pushHandler didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];} - (void)application:(UIApplication*)app didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{ PushNotification* pushHandler = [self.viewController getCommandInstance:@”PushNotification”]; [pushHandler didFailToRegisterForRemoteNotificationsWithError:error];} - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo{ PushNotification* pushHandler = [self.viewController getCommandInstance:@”PushNotification”]; NSMutableDictionary* mutableUserInfo = [userInfo mutableCopy]; // Get application state for iOS4.x+ devices, otherwise assume active UIApplicationState appState = UIApplicationStateActive; if ([application respondsToSelector:@selector(applicationState)]) { appState = application.applicationState;

5/12

Page 26: Appliness #8 – November 2012

} [mutableUserInfo setValue:@”0” forKey:@”applicationLaunchNotification”]; if (appState == UIApplicationStateActive) { [mutableUserInfo setValue:@”1” forKey:@”applicationStateActive”]; [pushHandler didReceiveRemoteNotification:mutableUserInfo]; } else { [mutableUserInfo setValue:@”0” forKey:@”applicationStateActive”]; [mutableUserInfo setValue:[NSNumber numberWithDouble: [[NSDate date] timeIntervalSince1970]] forKey:@”timestamp”]; [pushHandler.pendingNotifications addObject:mutableUserInfo]; }}/* STOP BLOCK */

The above code essentially creates a reference to our PushNotification class, sets or reads some values (not going into detail here to keep this less complicated), and calls different methods with parameters depending on the event that occurred.

The last thing you need to do is add a code fragment into the didFinishLaunchingWithOptions method in that same AppDelegate.m class to handle opening the application from a notification (and adding the received object to the pendingNotifications for later retrieval). Add this block right before the end return YES:

/* Handler when launching application from push notification */ // PushNotification - Handle launch from a push notification NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; if(userInfo) { PushNotification *pushHandler = [self.viewController getCommandInstance:@”PushNotification”]; NSMutableDictionary* mutableUserInfo = [userInfo mutableCopy]; [mutableUserInfo setValue:@”1” forKey:@”applicationLaunchNotification”]; [mutableUserInfo setValue:@”0” forKey:@”applicationStateActive”]; [pushHandler.pendingNotifications addObject:mutableUserInfo]; }/* end code block */

PUSHNOTIFICATION PLUGIN – JAVASCRIPT APIS

Now that you have the project setup complete including the native Objective-C handlers above, you can actually start coding with the Cordova PushNotification JavaScript interfaces. Below is further detail about some of them and examples of interacting with then in your code. Note: there are others that are available but not covered specifically yet in this post.

REGISTER DEVICE

The PhoneGap PushNotification plugin offers a registerDevice() API to register your application with Apple’s Push Notification Service to receive push notifications. In the function you specify exactly which types of notifications are enabled (alerts/badges/sounds). The result is a unique device token that can then be used by the server-side to send the notification to that device.

Apple recommends you register your application for push notifications on the device every time it’s run

6/12

Page 27: Appliness #8 – November 2012

since tokens can change. The documentation says: ‘By requesting the device token and passing it to the provider every time your application launches, you help to ensure that the provider has the current token for the device. If a user restores a backup to a device other than the one that the backup was created for (for example, the user migrates data to a new device), he or she must launch the application at least once for it to receive notifications again. If the user restores backup data to a new device or reinstalls the operating system, the device token changes. Moreover, never cache a device token and give that to your provider; always get the token from the system whenever you need it.’

An example of using the registerDevice() function is included in the sample project and is also shown be-low:

var pushNotification = window.plugins.pushNotification;pushNotification.registerDevice({alert:true, badge:true, sound:true}, function(status) { app.myLog.value+=JSON.stringify([‘registerDevice status: ‘, status])+”\n”; app.storeToken(status.deviceToken);});

Once the above code is in place and your application is run, you will receive an alert like the following prompting if it’s ok to receive push notifications (this results in a setting that can be modified in your de-vice settings as needed):

GET PENDING NOTIFICATIONS

Pending notifications are those notifications that are received while the application was not active. When the application is launched you will want to retrieve them so you can handle the data sent to you as needed. The getPendingNotifications() function is available in the API for that purpose. Below is some example code:

var pushNotification = window.plugins.pushNotification;pushNotification.getPendingNotifications(function(notifications) { app.myLog.value+=JSON.stringify([‘getPendingNotifications’, notifications])+”\n”; console.log(JSON.stringify([‘getPendingNotifications’, notifications]));});

GET NOTIFICATION STATUS

This method will return type and which notifications are enabled (alert, sound, badge).

var pushNotification = window.plugins.pushNotification;pushNotification.getRemoteNotificationStatus(function(status) { 7/

12

Page 28: Appliness #8 – November 2012

app.myLog.value+=JSON.stringify([‘Registration check - getRemoteNotificationStatus’, status])+”\n”;});

SET BADGE NUMBER

You will likely need to set the badge number on the application icon as you process the notifications, for instance if you open from a push notification just received, you may want to decrement or clear it. Setting the badge number to 0 will remove or clear the badge as shown below.

var pushNotification = window.plugins.pushNotification;app.myLog.value+=”Clear badge... \n”;pushNotification.setApplicationIconBadgeNumber(num);

ANATOMY OF AN APPLE PUSH NOTIFICATION

The maximum size for a notification payload is 256 bytes. If that limit is exceeded, it will be refused. Also note the delivery of notifications is “best effort” and not guaranteed, according to the Apple documenta-tion, so you should not use it for sending critical or sensitive data, only to notify that new data is available. The notification payload is a JSON dictionary object that needs to contain another dictionary identified by the key aps. The aps dictionary then will contain one or more properties that would specify an alert to display, a number badge to set on the application icon and/or a sound to play when the notification occurs. It’s also possible to create a custom payload but that is beyond the scope of this post. The alert object itself can contain just a string of text to display, OR a dictionary object with keys for a body, custom action button text to display and a custom launch image that can be set. More specific details about the payload can be found here.

Here’s an example of a simple payload in bytes:

A typical aps dictionary object will contain 3 properties; alert, badge and sound, such as shown in the fol-lowing output:

applicationLaunchNotification = 0;

applicationStateActive = 0;

aps = {

alert = {

“action-loc-key” = Play;

body = “Your turn!”;

“launch-image” = “mysplash.png”;

};

badge = 5;

sound = “notification-beep.wav”;

8/12

Page 29: Appliness #8 – November 2012

};

messageFrom = Holly;

timestamp = “1350416054.782263”;

Any custom sounds or launch images must be contained in the Resources folder in your project (under XCode)your projects Resources folder in XCode. For example in my image below, I have a notification-beep.wav and mysplash.png specified that I refer to in my push notification coming from the server.

SERVER-SIDE CODE HANDLING

LISTENING FOR DEVICE REGISTRATION TOKEN WITH NODE.JS

Below is example code you could use to get started with a server-side solution to handling device token registration which I currently call from my application sample to show how and at which point you might want to communicate with a 3rd party server to store device tokens after receiving the device token from Apple. Currently it doesn’t do anything with the token other than show that it and the message were re-ceived, but the next step would be to store the users’s device token and any other information in a data-base for later use when a push notification needs to be sent (such as shown in the next example). I plan to do a Part 2 series on integrating with MongoDB so check back soon!

var http = require(‘http’);var apn = require(‘apn’);var qs = require(‘querystring’); var server = http.createServer(function (req, res) { if(req.method === “POST”) {

9/12

Page 30: Appliness #8 – November 2012

var fullBody=””; req.on(‘data’, function(chunk) { fullBody += chunk; console.log(“Full body “ + fullBody); }); req.on(‘end’, function() { var data = qs.parse(fullBody); console.log(“Token “ +data.token); console.log(“Message “ + data.message); var myDevice = new apn.Device(data.token); // Now we need to store it! Add code to interface with a db below... res.writeHead(200, {“Content-Type”: “text/plain”}); res.end(“Thank you for registering\n”); res.end(); }); }}).listen(8888);console.log(“Server running at http:/ /127.0.0.1:”+server.address().port);

Note: I’m simply running this script using Node.js on my localhost. When testing from your actual device (since push notifications are not supported in the emulator), you can set up a Manual HTTP Proxy in your device’s Wi-Fi settings to point to the IP Address of your computer. Go to your Wi-Fi network and scroll to the bottom of the settings to set the Manual Proxy server and port. Here’s an example of mine:

10/1

2

Page 31: Appliness #8 – November 2012

SENDING A NOTIFICATION WITH ARGON (NODE.JS API)

Below is an example of some simple code to show how you could use the argon open source Node.js API to send a push notification to a users device. I simply hard-coded my device tokens in for quick testing, but ultimately you would be retrieving them from a database (after being stored above) to use for send-ing the push notifications.

var http = require(‘http’);var apn = require(‘apn’);var url = require(‘url’); var myPhone = “d2d8d2a652148a5cea89d827d23eee0d34447722a2e7defe72fe19d733697fb0”;var myiPad = “51798aaef34f439bbb57d6e668c5c5a780049dae840a0a3626453cd4922bc7ac”; var myDevice = new apn.Device(myPhone); var note = new apn.Notification();note.badge = 1;note.sound = “notification-beep.wav”;note.alert = { “body” : “Your turn!”, “action-loc-key” : “Play” , “launch-image” : “mysplash.png”};note.payload = {‘messageFrom’: ‘Holly’}; note.device = myDevice; var callback = function(errorNum, notification){ console.log(‘Error is: %s’, errorNum); console.log(“Note “ + notification);}var options = { gateway: ‘gateway.sandbox.push.apple.com’, // this URL is different for Apple’s Production Servers and changes when you go to production errorCallback: callback, cert: ‘PushNotificationSampleCert.pem’, key: ‘PushNotificationSampleKey.pem’, passphrase: ‘myPassword’, port: 2195, enhanced: true, cacheLength: 100 }var apnsConnection = new apn.Connection(options);apnsConnection.sendNotification(note);

The above code will produce a notification that looks like the following

on my device if you have your device

Settings->Notifications->MyAppName set to Alerts:

11/1

2

Page 32: Appliness #8 – November 2012

If you’re device settings for Alert Style on the application is set to Banners, it will look like this:

Important Note: You need to change the .pem files to your cert and private key created in the setup (the ones you ultimately combined into a single .pem with instructions from here. Remember you first con-verted the .cer to a .pem, and then your .p12 to a .pem, those are the two files needed here – see this readme for more details on argon parameters). In my example, my .pem files are in the same folder as my Node.js code. You can omit the password property if you did not keep a password on them.

There’s also a PHP Push Notifications API called APNS-PHP if you prefer to use PHP as your language of choice…

SAMPLE PROJECT

I’ve included a link to a sample project on GitHub that I created for a reference application since it includes everything discussed above already in place. You can’t actually use this project out of the box because you have to have your own uniqe App ID and Provisioning files set on your project for it so you are bet-ter off starting your own project from scratch and using mine for reference only. I created this project to eventually be cross-platform using the cordova-client tool, but currently only iOS is setup so refer to the PGPushNotificationSample/platforms/ios path for the iOS specific code. You’ll find all of the JavaScript functions in the PGPushNotificationSample/platforms/ios/www/js/index.js file. I chose straight JavaScript in favor of simplicity. It also does an XMLHttpRequest to my simple server code (example shown above) and sends the device token received from the registration.

Page 33: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Nicholas Zakas

DOES JAVASCRIPT NEED CLASSES?IN THIS ARTICLE, NICHOLAS CLEARS UP CONFUSION AROUND THE TERMINOLOGY OF CLASSES (OR LACK THEREOF) WHEN CODING IN JAVASCRIPT.

CLASSLESS JAVASCRIPT

Like it or not, ECMAScript 6 is going to have classes[1]. The concept of classes in JavaScript has always been polarizing. There are some who love the classless nature of JavaScript specifically because it is dif-ferent than other languages. On the other hand, there are those who hate the classless nature of JavaS-cript because it’s different than other languages. One of the biggest mental hurdles people need to jump when moving from C++ or Java to JavaScript is the lack of classes, and I’ve had people explain to me that this was one of the reasons they either didn’t like JavaScript or decided not to continue learning.

JavaScript hasn’t had a formal definition of classes since it was first created and that has caused confusion right from the start. There are no shortage of JavaScript books and articles talking about classes as if they were real things in JavaScript. What they refer to as classes are really just custom constructors used to define custom reference types. Reference types are the closest thing to classes in JavaScript. The general format is pretty familiar to most developers, but here’s an example:

function MyCustomType(value) { this.property = value;}

MyCustomType.prototype.method = function() { return this.property;};

Page 34: Appliness #8 – November 2012

In many places, this code is described as declaring a class named MyCustomType. In fact, all it does is declare a function named MyCustomType that is intended to be used with new to create an instance of the reference type MyCustomType. But there is nothing special about this function, nothing that says it’s any different from any other function that is not being used to create a new object. It’s the usage of the function that makes it a constructor.

The code doesn’t even look like it’s defining a class. In fact, there is very little obvious relationship be-tween the constructor definition and the one method on the prototype. These look like two completely separate pieces of code to new JavaScript developers. Yes, there’s an obvious relationship between the two pieces of code, but it doesn’t look anything like defining a class in another language.

Even more confusing is when people start to talk about inheritance. Immediately they start throwing around terms such as subclassing and superclasses, concepts that only make sense when you actually have classes to work with. Of course, the syntax for inheritance is equally confusing and verbose:

function Animal(name) { this.name = name;}

Animal.prototype.sayName = function() { console.log(this.name);};

function Dog(name) { Animal.call(this, name);}

Dog.prototype = new Animal(null);Dog.prototype.bark = function() { console.log(“Woof!”);};

The two-step inheritance process of using a constructor and overriding a prototype is very confusing.

In the first edition of Professional JavaScript for Web Developers, I used the term “class” exclusively. The feedback I received indicated that people found this confusing and so I changed all references to “class” in the second edition to “type”. I’ve used that terminology ever since and it helps to eliminate a lot of the confusion.

However, there is still a glaring problem. The syntax for defining custom types is confusing and verbose. Inheritance between two types is a multistep process. There is no easy way to call a method on a super-type. Bottom line: it’s a pain to create and manage custom types. If you don’t believe that this is a prob-lem, just look at the number of JavaScript libraries that have introduced their own way of defining custom types, inheritance, or both:

•YUI – has Y.extend() to perform inheritance. Also adds a superclass property when using this method.[2]

•Prototype – has Class.create() and Object.extend() for working with objects and “classes”.[3]

•Dojo – has dojo.declare() and dojo.extend().[4]

•MooTools – has a custom type called Class for defining and extending classes.[5]

It’s pretty obvious that there’s a problem when so many JavaScript libraries are defining solutions. Defin-ing custom types is messy and not at all intuitive. JavaScript developers need something better than the current syntax.

ECMAScript 6 classes are actually nothing more than syntactic sugar on top of the patterns you are al-ready familiar with. Consider this example: 2/

4

Page 35: Appliness #8 – November 2012

class MyCustomType { constructor(value) { this.property = value; }

method() { return this.property; }}

This ECMAScript 6 class definition actually desugars to the previous example in this post. An object cre-ated using this class definition works exactly the same as an object created using the constructor defini-tion from earlier. The only difference is a more compact syntax. How about inheritance:

class Animal { constructor(name) { this.name = name; }

sayName() { console.log(this.name); }}

class Dog extends Animal { constructor(name) { super(name); }

bark() { console.log(“Woof!”); }}

This example desugars to the previous inheritance example. The class definitions are compact and the clunky multistep inheritance pattern has been replaced with a simple extends keyword. You also get the benefit of super() inside of class definitions so you don’t need to reference the supertype in more than one spot.

All of the current ECMAScript 6 class proposal is simply new syntax on top of the patterns you already know in JavaScript. Inheritance works the same as always (prototype chaining plus calling a supertype constructor), methods are added to prototypes, and properties are declared in the constructor. The only real difference is less typing for you (no pun intended). Class definitions are just type definitions with a different syntax.

So while some are having a fit because ECMAScript 6 is introducing classes, keep in mind that this con-cept of classes is abstract. It doesn’t fundamentally change how JavaScript works; it’s not introducing a new thing. Classes are simply syntactic sugar on top of the custom types you’ve been working with for a while. This solves a problem that JavaScript has had for a long time, which is the verbosity and confusion of defining your own types. I personally would have liked to use the keyword type instead of class, but at the end of the day, this is just a matter of semantics.

So does JavaScript need classes? No, but JavaScript definitely needs a cleaner way of defining custom types. It just so happens the way to do that has a name of “class” in ECMAScript 6. And if that helps de-velopers from other languages make an easier transition into JavaScript, then that’s a good thing.

3/4

Page 36: Appliness #8 – November 2012

ABOUT THIS ARTICLE

Nicholas C. Zakas is a front-end consultant, author and speaker. He worked at Yahoo! for almost five years, where he was front-end tech lead for the Yahoo! homepage and a contributor to the YUI li-brary. He is the author of Maintainable JavaScript (O’ Reilly, 2012), Professional JavaScript for Devel-opers (Wrox, 2012), High Performance JavaScript (O’Reilly, 2010), and Professional Ajax (Wrox, 2007). http://www.nczonline.net/

@slicknet

Maintainable JavaScripthttp://www.amazon.com

JavaScript for Developershttp://www.amazon.com/

High Performance JavaScript (Build Faster Web Application Interfaces)http://www.amazon.com

ONLINE RESOURCES

REFERENCES

1. Maximally minimal classes (ECMA)

2. YUI extend() (YUILibrary)

3. Prototype Classes and Inheritance (Prototype)

4. Creating and Enhancing Dojo Classes (SitePen)

5. MooTools Class (MooTools)

Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in

any way, reflect those of my employer, my colleagues, Wrox Publishing, O’Reilly Publishing, or anyone else. I speak

only for myself, not for them.

Page 37: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Piotr Walczyszyn

NATIVE SCROLLING IN JQUERY MOBILE/PHONEGAP APPLICATIONSPIOTR DISCUSSES SOME TECHNIQUES FOR HANDLING SCROLLING WHEN DEVELOPING MOBILE APPS USING PHONEGAP AND JQUERY MOBILE FOR IOS AND ANDROID.

In one of my previous blog posts, I covered how to fix flickers and jumps during page transitions when using jQuery Mobile with PhoneGap. The good news is that flickers were eliminated with latest release of PhoneGap 2.1 and its departure from using IFrame for JavaScript to Native bridge. Unfortunately, the issue of 1px jumps is still there, but that is by design in jQuery Mobile. So, this means my solution with additional div element hosting application content is still valid.

Unfortunately, my approach has a drawback of losing jQuery Mobile out-of-the-box content scrolling. A workaround I found for this is to use absolute positioning and native css declarable scrolling. By native css declarable scrolling, I understand using the overflow property with the scroll value and -webkit-overflow-scrolling set to touch. You have to be careful when using these, as it may not work on all devices. I know iOS supports it from version 5 and above. In case of Android only overflow: scroll is actually working, which means you will not have a rubber band effect, but your content will actually scroll – which in case of Android is often good enough. For devices that don’t support it, you may want to use the Overthrow library which nicely polyfills it, or any other libs like: iScroll, Scrollability or ScrollView.

The snippet below demonstrates it in detail, you can also run it from here. As you can see, I had to ab-solutely position the header and content elements. In addition, I added the .scrollable css class that enables native scrolling of its content. One thing to note here is that I had to enforce hardware acceleration of scrolled elements with -webkit-transform: translateZ(0px); property. This only works on iOS so make sure you don’t use this declaration on Android. BTW, Apple has fixed it in iOS 6 and enforcing hardware acceleration will not be necessary in the future.

Page 38: Appliness #8 – November 2012

<<

< Y

OU

CA

N S

CR

OLL

DO

WN

TH

E C

ON

TEN

T O

F TH

IS F

RA

ME

>>

>

Try me!

2/2

Page 39: Appliness #8 – November 2012

PAUL D. HUNTDESIGNER OF SOURCE CODE PRO

“In designing Source Code Pro, I tried to resolve many of the things that bothered me personally in other designs.”

EXCLUSIV

E INTERVIE

W

Cop

yrig

ht -

Rey

Rey’s

Pho

togr

aphy

1/3

Page 40: Appliness #8 – November 2012

HI PAUL, CAN YOU INTRODUCE YOURSELF TO OUR READERS? HOW DID YOU BECOME A FONT DESIGNER?

I started into type design out of curiosity. I wanted to find out what it takes to make a font and so I found some tutorials online and began with experimenting with drawing Cyrillic characters for existing freeware fonts. In my online searches I came across the Typophile web forums, which were quite active at the time, and was able to learn a lot by posing questions directly to designers and developers working in typeface design.

As part of my self-guided type education, I taught myself how to do OpenType programming. With this skill in hand, I was presented with the rare opportunity to work as an intern for a type foundry. My stint with P22 Type Foundry quickly morphed from an internship to a full-time job and I remained there for three years. After that time, I felt that I had a good base in the technical aspects of type production, but wanted to focus more on learning the design aspects.

At that point, I felt that the best option for me to do this was to enroll in the Masters course in typeface design at the University of Reading, UK. There I was able to work on my digital letter drawing skills and learned to better understand how to create a cohesive visual language for writing systems. After graduation, Adobe asked me to come work for them and I have been here ever since continuing to build on my skills in both programming and designing fonts.

YOU DESIGNED A FONT FOR CODERS. HOW DID YOU IDENTIFY WHAT DEVELOPERS EXPECT?

In designing a monospaced typeface, I drew primarily from my own experience using such fonts. As you can gather from my personal story, it was my ability to do some coding that helped me to find my way into typeface design.

Much of my time spent in developing fonts is in editing text files, which are used by our tools to compile font software. So I’m familiar with the shortcoming of many of the existing monospaced fonts. In designing Source Code Pro, I tried to resolve many of the things that bothered me personally in other designs. Also, I got very good feedback in working directly with the Brackets team, for whom we created this font family.

Discover Source Code Pro:0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

2/3

Page 41: Appliness #8 – November 2012

WHAT MAKES SOURCE CODE PRO A UNIQUE FONT?

In terms of design, I’m not sure how unique this type family is. I tried to keep the details as simple as possible as I find a common problem with many monospaced fonts is that they feature too many distracting elements.

I also tried to make the type design more readable by giving the letterforms more pleasing proportions. That said, there are other fonts that do these things. However, I feel that as a open source project this type family is truly unique as we have tried to make the font sources as accessible as possible so that other parties can customize this project as needed.

WHAT ARE THE BENEFITS OF AN OPEN-SOURCE FONT? DESIGNERS CAN FORK THE PROJECT ? :)

In terms of benefits to Adobe, I feel that our open source font projects have generated quite a bit of good will in the design and developer communities that we are trying to connect with. Also making Source Code and its sister family Source Sans Pro open source provides better type options for our own open source projects that need fonts for UI.

These projects, due to their open nature, can also be used as learning tools for people wanting to learn how to develop fonts. Lastly, because these projects are open, other parties can help contribute to their success. We recently added more functionality to the Source Sans family with the help and support of a third party, Logos Bible Software. The work that they commissioned can benefit us as well as all users of these fonts.

ARE YOU CURRENTLY WORKING ON A NEW FONT?

I am continuing to extend the functionality of the Source family of fonts, and I see that there is possibility for this to continue for the next several years. Currently I am drawing Greek and Cyrillic characters for the Source Sans family and I hope that these additions will eventually make their way into the Source Code fonts as well. In addition to this work, I just finished a typeface family for Gurmukhi script.

And that’s all the design work I’m doing at the moment, but there is always more font development work for me whether I’m drawing or not. This means I’ll be looking at a lot of monospaced text... :^D

Get Source Code Pro:https://github.com/adobe/Source-Code-Pro

3/3

Page 42: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Karl Sequin

NODE.JS, REQUIRE AND EXPORTSIN THIS ARTICLE, KARL SHARES WHAT HE HAS LEARNED FROM USING NODE.JS IN CONJUNCTION WITH REQUIRE TO EXPOSE CODE ELEMENTS TO OTHER MODULES.

Back when I first started playing with node.js, there was one thing that always made me uncomfortable. Embarrassingly, I’m talking about module.exports. I say embarrassingly because it’s such a fundamental part of node.js and it’s quite simple. In fact, looking back, I have no idea what my hang up was...I just

remember being fuzzy on it. Assuming I’m not the only one who’s had to take a second, and third, look at it before it finally started sinking in, I thought I could do a little write up.

In Node, things are only visible to other things in the same file. By things, I mean variables, functions, classes and class members. So, given a file misc.js with the following contents:

var x = 5;var addX = function(value) { return value + x;};

Another file cannot access the x variable or addX function. This has nothing to do with the use of the var keyword. Rather, the fundamental Node building block is called a module which maps directly to a file. So we could say that the above file corresponds to a module named file1 and everything within that module (or any module) is private.

Page 43: Appliness #8 – November 2012

Now, before we look at how to expose things out of a module, let’s look at loading a module. This is where require comes in. require is used to load a module, which is why its return value is typically as-signed to a variable:

var misc = require(‘./misc’);

Of course, as long as our module doesn’t expose anything, the above isn’t very useful. To expose things we use module.exports and export everything we want:

var x = 5;var addX = function(value) { return value + x;};module.exports.x = x;module.exports.addX = addX;

Now we can use our loaded module:

var misc = require(‘./misc’);console.log(“Adding %d to 10 gives us %d”, misc.x, misc.addX(10));

There’s another way to expose things in a module:

var User = function(name, email) { this.name = name; this.email = email;};module.exports = User;

The difference is subtle but important. See it? We are exporting user directly, without any indirection. The difference between:

module.exports.User = User;//vsmodule.exports = User;

is all about how it’s used:

var user = require(‘./user’);

var u = new user.User();//vsvar u = new user();

It’s pretty much a matter of whether your module is a container of exported values or not. You can actu-ally mix the two within the same module, but I think that leads to a pretty ugly API.

Finally, the last thing to consider is what happens when you directly export a function:

var powerLevel = function(level) { return level > 9000 ? “it’s over 9000!!!” : level;};module.exports = powerLevel;

2/3

Page 44: Appliness #8 – November 2012

ABOUT THIS ARTICLE

My name is Karl Sequin, I’m a software developer and amateur writer. I contribute to various open source projects, run a few side projects and enjoy learning new technologies.

http://openmymind.net/

@karlsequin

Node.jshttp://nodejs.org/

RequireJShttp://requirejs.org/

Karl’s bloghttp://openmymind.net/

ONLINE RESOURCES

When you require the above file, the returned value is the actual function. This means that you can do:

require(‘./powerlevel’)(9050);

Which is really just a condensed version of:

var powerLevel = require(‘./powerlevel’)powerLevel(9050);

Hope that helps!

Page 45: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Karl Sequin

NODE.JS, MODULE.EXPORTS AND ORGANIZING EXPRESS.JS ROUTESA WHILE AGO I WROTE A POST EXPLAINING HOW REQUIRE AND MODULE.EXPORTS WORK. TODAY I WANTED TO SHOW A PRACTICAL EXAMPLE OF HOW WE CAN USE THAT KNOWLEDGE TO ORGANIZE ROUTES IN AN EXPRESS.JS PROJECT.

To recap the original post, module.exports is how we make something within our file publicly accessible to anything outside our file. We can export anything: a class, a hash, a function or a variable. When you require something you get whatever it exported. That means that the return value from require can

be a class, a hash, a function or a variable. The end result is that how the value returned from require is used can vary quite a bit:

# the user file exported a classUser = require(‘./models/user’)leto = new User()

# the initialize file exported a functioninitliaze = require(‘./store/inialize’)initialize(config)

# the models file exported as hash (which has a User key which was an object)Models = require(‘./models’)user = new Models.User()

Page 46: Appliness #8 – November 2012

With that in mind, I happen to be building a website that’ll have two distinct sections: an API and a user-facing portal. I’d like to organize my routes/controllers as cleanly as possible. The structure that I’d like is:

/routes/routes/api//routes/api/stats.coffee/routes/api/scores.coffee

/routes/portal//routes/portal/users.coffee/routes/portal/stats.coffee

This is very Rails-esque with controller namespaces and resources. Ideally, I’d like controllers under API (stats and scores) to have access to common API-based methods. How can we cleanly achieve this?

Before we can dive any further we need to understand how express loads routes. You basically attach the route to the express object. The simplest example might look something like:

express = require(‘express’)app = express.createServer()app.configure -> app.use(app.router)

app.get ‘/’, (req, res) -> res.send(‘hello world’)

On line 4 we tell express to enable its routing, and then use the get and post methods (to name a few) to define our routes.

Taking a baby step, if we wanted to extract our route into its own file, we could do:

# routes.coffeemodule.exports = (app) -> app.get ‘/’, (req, res) -> res.send(‘hello world’)

# and use it like so:express = require(‘express’)app = express.createServer()app.configure -> app.use(app.router)require(‘./routes’)(app)

The syntax might be strange, but there’s nothing new here. First, our exports isn’t doing anything other than exporting a function that takes a single parameter. Secondly, our require is loading that function and executing it. We could have rewritten the relevant parts more verbosely as:

# routes.coffeeroutes: (app) -> ....module.exports = routes

# and use it like so:routes = require(‘./routes’)routes(app)

2/5

Page 47: Appliness #8 – November 2012

So how do we take this to the next level? Well, we don’t want to have to import a bunch of different routes at the base level. We want to use require(‘./routes’)(app) and let that load all the neces-sary routes. So, the first thing we’ll do is put an index file in a routes folder:

# routes/index.coffeemodule.exports = (app) -> require(‘./api’)(app) require(‘./portal’)(app)

When you tell node.js to require a folder, it automatically loads its index file. With the above, our initial route loading remains untouched: require(‘./routes’)(app). Now, this loading code doesn’t just include routes/index.coffee it actually executes it (it’s calling the function and passing in the app as an argument). All our routes function does is load and execute more functions.

For both our API and portal, we can do the same thing we did for routes:

# routes/api/index.coffeemodule.exports = (app) -> require(‘./stats’) require(‘./scores’)

Stats and scores can contain actual routes:

# routes/api/scores.coffeemodule.exports = (app) -> app.post ‘/api/scores’, (req, res) -> # save as score

app.get ‘/api/scores’, (req, res) -> # get scores

# routes/api/stats.coffeemodule.exports = (app) -> app.post ‘/api/stats’, (req, res) -> # save a stat

This is a good solution to help us organize our code, but what about sharing behavior? For example, many API functions will want to make sure requests are authenticate (say, using an SHA1 hash of the pa-rameters and signature).

Our first attempt will be to add some utility methods to the api/index.coffee file:

# routes/api/index.coffee

routes = (app) -> require(‘./stats’) require(‘./scores’)

signed = (req, res, next) -> if is_signed(req) next() else res.send(‘invalid signature’, 400)

is_signed = (req) -> #how to sign a request isn’t the point of this port

3/5

Page 48: Appliness #8 – November 2012

module.exports = routes: routes signed: signed

Since we are now exporting a hash rather than a function, our routes/index.coffee file also needs to change:

# OLD routes/index.coffeemodule.exports = (app) -> require(‘./api’)(app) require(‘./portal’)(app)

# NEW routes/index.coffeemodule.exports = (app) -> require(‘./api’).routes(app) require(‘./portal’).routes(app) #assuming we do the same to portal

Now, we can use our signed method from our scores route:

# routes/api/scores.coffeeapi = require(‘./index’)

module.exports = (app) -> app.post ‘/api/scores’, api.signed, (req, res) -> # save as score

For those who don’t know, when an express route is given 3 parameters, the 2nd one is treated as some-thing of a before-filter (you can pass in an array of them and they’ll be processed in order).

This solution is pretty good, but we can take it a step further and create some inheritance. The main ben-efit is not having to specify api. all over the place. So, we change our api/index.coffee one last time:

# routes/api/index.coffee

routes = (app) -> require(‘./stats’) require(‘./scores’)

class Api @signed = (req, res, next) => if @is_signed(req) next() else res.send(‘invalid signature’, 400)

@is_signed = (req) -> #how to sign a request isn’t the point of this port

module.exports = routes: routes Api: Api

4/5

Page 49: Appliness #8 – November 2012

ABOUT THIS ARTICLE

My name is Karl Sequin, I’m a software developer and amateur writer. I contribute to various open source projects, run a few side projects and enjoy learning new technologies.

http://openmymind.net/

@karlsequin

Node.jshttp://nodejs.org/

RequireJShttp://requirejs.org/

Karl’s bloghttp://openmymind.net/

ONLINE RESOURCES

Since the routes are still exposed the same way, we don’t have to change the main routes/index.coffee file. However, we can change our scores files like so:

class Scores extends require(‘./index’).Api @routes: (app) => app.post ‘/api/scores’, @signed, (req, res) -> # save as score

module.exports = Scores.routes

And that, is that. There’s a lot going on in all of this, but the key takeaway is that you can export anything and that flexibility can lead to some fairly well organized code. You can also leverage the fact that the index file is automatically loaded when its folder is required to keep things nice and clean.

I know this jumped all over the place, but hopefully you’ll find it helpful!

Page 50: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Andrew Trice

PHONEGAP, APPLE REJECTIONS & UI/UX GUIDELINESREAD HOW TO GET YOUR PHONEGAP APPLICATION APPROVED BY APPLE.

REJECTION

I’ve recently encountered some grumblings from the development community that Apple has rejected their PhoneGap apps for not being “native enough”. By itself, that doesn’t surprise me too much – Ap-ple has very strict rules/guidelines on what they will and will not accept into the App Store. What did surprise me is that people were blaming PhoneGap as the reason. This accusation is not accurate, and in this post I’ll attempt to clear things up.

APPLE & HTML

First, let’s talk about Apple & HTML. Apple does not reject applications because their user interface is built using HTML. In fact, many of Apple’s own apps or advertising platforms for iOS are entirely built with HTML/CSS/JS. For instance, the Apple Store and iAd advertising platform, among others, use HTML as the primary content for the user interface. Outside of Apple there are many successful apps that have user interfaces built with HTML, including LinkedIn, Wikipedia, the BBC Olympics, and many, many others.

Note: Not all these apps mentioned use PhoneGap, but they do use HTML for the UI.

Page 51: Appliness #8 – November 2012

Apple will reject applications that do not have a user experience that feels like an “app”, does not feel “at home” in the iOS ecosystem, or offers no advantage over a mobile web experience. This applies to all apps, not just apps developed using HTML for the UI. I don’t work for Apple, so I don’t know what their exact approval rules are (beyond these and these) but I can guarantee you that it largely comes down to how the user interacts with the app and how it “feels” on the device.

The iOS User Interface Guidelines from Apple have a very large amount of information about what is and what is not acceptable for Apple’s ecosystem. In these UI Guidelines, Apple specifically addresses “web-based designs”:

Reconsider Web-Based Designs

If you’re coming from the web, you need to make sure that you give people an iOS app experience, not a web experience. Remember, people can visit your website on their iOS-based devices using Safari on iOS.

Here are some strategies that can help web developers create an iOS app:

Focus your app. Websites often greet visitors with a large number of tasks and options from which they can choose, but this type of experience does not translate well to iOS apps. iOS users expect an app to do what it advertises, and they want to see useful content immediately.

Make sure your app lets people do something. People might enjoy viewing marketing content in the websites they visit, but they expect to accomplish something in an app.

Design for touch. Don’t try to replicate web UI design paradigms in your iOS app. Instead, get familiar with the UI elements and patterns of iOS and use them to showcase your content. Web elements you’ll need to re-examine include menus, interactions initiated by hovering, and links.

Let people scroll. Most websites take care to display the most important information in the top half of the page where it is seen first (“above the fold”), because people sometimes leave a page when they don’t find what they’re looking for near the top. But on iOS-based devices, scrolling is an easy, expected part of the experience. If you reduce font size or squeeze controls to fit your content into the space of a single device screen, you’re likely to end up with unreadable content and an unusable layout.

Relocate the homepage icon. Websites often display an icon that links to the homepage at the top of every webpage. iOS apps don’t include homepages, so this behavior is unnecessary. In addition, iOS apps allow people to tap the status bar to quickly scroll back to the top of a long list. If you center a tap-pable home icon at the top of the screen, it’s very difficult for users to tap the status bar instead.

In addition to the iOS User Interface Guidelines, Apple’s App Store Review Guidelines have additional tips for getting your apps approved. Many relate to HTML-based experiences, including:

2.7: Apps that download code in any way or form will be rejected

2.12: Apps that are not very useful, unique, are simply web sites bundled as Apps, or do not provide any lasting entertainment value may be rejected

10.3: Apps that do not use system provided items, such as buttons and icons, correctly and as described in the Apple iOS Human Interface Guidelines may be rejected

10.6: Apple and our customers place a high value on simple, refined, creative, well thought through in-terfaces. They take more work but are worth it. Apple sets a high bar. If your user interface is complex or less than very good, it may be rejected

12.3: Apps that are simply web clippings, content aggregators, or a collection of links, may be rejected

As I mentioned earlier, I don’t know all of Apple’s rules, but I do know this:

- If your app is just a web site wrapped in PhoneGap, it will probably get rejected. There are excep- 2/3

Page 52: Appliness #8 – November 2012

tions to this case, but don’t expect that wrapping a web site in a web view will get you into the App Store.

- If your app requires the user to pinch/zoom/pan to view content (like a web site), it will probably get rejected. Your apps need to feel like apps.

- If your app just looks like text on a page with hyperlinks, and has no native-like styles, it will probably get rejected.

App store approval often seems like a blurry line, and is very much subjective to the apps that are being evaluated.

PHONEGAP

Now, let’s examine what PhoneGap is exactly, and how it fits into this context… From the PhoneGap FAQ: “PhoneGap is an open source solution for building cross-platform mobile apps with standards-based Web technologies like HTML, JavaScript, CSS.” For a much more detailed description of PhoneGap, see my previous post “PhoneGap Explained Visually”. PhoneGap acts as a container for user interface elements built with HTML, CSS, and JavaScript. It wraps your HTML experience and provides the ability to interact with native operating system functionality from JavaScript. PhoneGap also provides the ability to pack-age your application archive for App Store distribution.

PhoneGap does not make any attempt to build your UI for you. PhoneGap applications are not going to be immediately accepted because the user interface is built with web technologies. PhoneGap does not absolve you from following Apple’s rules/guidelines.

When you build PhoneGap applications, it is up to the designer or developer to build apps that corre-spond to the UI/UX guidelines for a particular platform/ecosystem. There are many tools and frameworks that you can use to make your HTML experiences feel more native. Here are just a few:

Twitter Bootstrap

iUI

jQuery Mobile

Sencha Touch

Kendo UI

app-UI

Zurb Foundation

Moobile

Chocolate Chip UI

Dojo Toolkit

jqMobi

Page 53: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Kianosh Pourian

WHY ARE PREPROCESSORS SO DIVISIVE?IN THIS ARTICLE, KIANOSH POURIAN, OPENS UP THE DISCUSSION ON THE VALUE OF PRE-PROCESSORS, WHAT THEY ARE AND HOW AND WHEN THEY SHOULD BE USED. HE ALSO POINTS US TO SOME VALU-ABLE RESOURCES ON SOME TOOLS WE SHOULD BE LOOKING AT.

BACKGROUND

The genesis of this article is from a disagreement between me and a co-worker on the use of Sass CSS. This was during a project where as the UI Architect, I had decided on using Sass CSS. After a designer was brought on board, he did not want to use Sass. The discussion went something like this:

Designer guy: I am not familiar with Sass CSS.

Me: Here is some information on it.

Designer guy: Compile my CSS? I don’t want to compile my CSS.

Me: Just use the ‘watch’ feature.

Designer guy: I can’t debug my CSS in the browser.

Me: Use FireSass (For Firefox only).

Designer guy: I don’t want to use Sass CSS.

Me: WE ARE USING SASS.

Designer guy: Sass is just a fad.

Me: We are using Sass.

Page 54: Appliness #8 – November 2012

Multiple meetings were held that followed the same pattern as above. Looking back, I wish the discus-sions had gone a different way. Not in the sense that who was right or wrong but in the sense that it could have been handled better. Introspectively, I could have done better.

Later on at the Backbone Conference in Boston, there were a couple of presenters that made statements like “CoffeeScript, you either love it or hate it”. This got me thinking, why should that be? Why are we in such polarized opinions when it comes to pre-processors in front end development? We are not the US Congress or the Senate for that matter. This got me thinking and started me on a path to find a peaceful solution to this issue.

CAN YOU DEFINE PRE-PROCESSORS PLEASE?

In researching for this blog, I looked up the word pre-processors and found a lot of information. Wikipe-dia defines it as:

“In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often

used by some subsequent programs like compilers. The amount and kind of processing done depends on the nature of the preprocessor; some preprocessors are only capable of performing relatively simple textual substitutions and macro expansions, while others have the power of full-fledged programming languages.”

By this definition, any work done on the code before compilation is the job of the preprocessor. There are two types of preprocessing:

1. Lexical: This is typically macro substitution, text inclusion, conditional compilation, etc…

2. Syntactical: Syntactical preprocessing’s role is to transform syntax trees according to user defined rules.

In the realm of front end development, most of the pre-processing tools are of the syntactical type. How-ever, stepping out of the computer science field, preprocessing exists in many areas of our lives. Couldn’t any encryption or decryption of code be considered as a preprocessor to gaining the underlying infor-mation. When a court stenographer types all the information in the court, wouldn’t that be considered a form pre-processing? How about short hand notes?

WHAT TOOLS ARE AVAILABLE?

In front end development, there has been an increase in the number of preprocessing tools thereby caus-ing a bit of a polarized attitude towards them, not just whether to use any preprocessing tools but also which one. The tools that are available are as such:

HTML

•HAML: (HTML Abstraction Markup Language) is a lightweight markup language that is used to describe the XHTML of any web document without the use of traditional inline coding. It’s designed to address many of the flaws in traditional templating engines, as well as making markup as elegant as it can be.

•Jade: Jade is a high performance template engine heavily influenced by Haml and implemented with JavaScript for node.

•Zen-coding: In this post we present a new speedy way of writing HTML code using CSS-like selector syntax — a handy set of tools for high-speed HTML and CSS coding. It was developed by our author Sergey Chikuyonok.

2/3

Page 55: Appliness #8 – November 2012

ABOUT THIS ARTICLE

I am a native born Iranian and reside in Boston Mas-sachusetts. Husband to a lovely New Englander and father to two lovely girls. In my spare time, I am an enthusiast in all things involving UI development and am lucky enough to be working in that field for cli-ents like VMWare, MIT, and Novartis.http://innovatorylife.com/

@kianoshp

HAML - HTML Abstraction Markup Languagehttp://haml.info/

SASShttp://sass-lang.com/

CoffeeScripthttp://coffeescript.org/

ONLINE RESOURCES

CSS

•Sass/Compass: Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-frame-work plugin. Compass is an open-source CSS Authoring Framework.

•LESS: extends CSS with dynamic behavior such as variables, mixins, operations and functions. LESS runs on both the client-side (Chrome, Safari, Firefox) and server-side, with Node.js and Rhino.

•Stylus

JAVASCRIPT

•CoffeeScript: CoffeeScript is a little language that compiles into JavaScript. Underneath all those awk-ward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. Coffee-Script is an attempt to expose the good parts of JavaScript in a simple way.

•IcedCoffeeScript: IcedCoffeeScript is a superset of CoffeeScript. The iced interpreter is a drop-in re-placement for the standard coffee interpreter; it will interpret almost all existing CoffeeScript programs.

•Dart: Dart is a new web programming language with libraries, a virtual machine, and tools. Dart helps developers build structured modern web apps. Dart compiles to JavaScript to run across the entire modern web.

•GWT: Google Web Toolkit (GWT) is a development toolkit for building and optimizing complex browser-based applications. GWT is used by many products at Google, including Google AdWords and Orkut. It’s open source, completely free, and used by thousands of developers around the world.

Page 56: Appliness #8 – November 2012

FOLLOW

US

BECOME A

FAN O

F

APPLINESS

JOIN THE APPLINESS COMMUNITY

APPLINESS IS A DIGITAL MAGAZINE WRITTEN BY PASSIONATE WEB DEVELOPERS.YOU CAN FOLLOW US ON YOUR FAVORITE SOCIAL NETWORK.

YOU CAN SUBSCRIBE TO OUR MONTHLY NEWSLETTER.YOU CAN CONTRIBUTE AND PUBLISH ARTICLES.

YOU CAN SHARE YOUR BEST IDEAS.YOU CAN BECOME APPLI.FOLLOW

US CON

TRIB

UTE

- FACEBOOK PAGE

- ON TWITTER

- ON GOOGLE+

- OUR NEWSLETTER

- CONTACT US

- SHARE AN IDEA

- WRITE AN ARTICLE

- BASH US

Page 57: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Jeremy Kahn

HACKING JAVASCRIPT’S FORMAL PARAMETERS WITH FUNCTION.APPLY()IN THIS ARTICLE, JEREMY PRESENTS SOME METHODS TO HELP CLEANUP JAVASCRIPT CODE AND MAKE IT MORE EFFICIENT.

PARAMETERS

Lately, I’ve been changing my coding habits to use configuration objects whenever possible in my code. In plain english, a configuration object is an object that you pass in as a formal parameter, instead of a list of separate parameters. This is useful for a number of reasons:

•It makes your code more flexible

•It is more semantic (easier to read)

•It makes your code cleaner

This what a typical function definition and call looks like, with a laundry list of paramters:

function ugly (a, b, c, d, e) { // logic...}ugly (this, “has”, 5, “parameters”, “without context”);

Page 58: Appliness #8 – November 2012

And this is a significantly nicer looking definition and call with a configuration object:

function pretty (config) { // logic...}

pretty ({ context: this, verb: “is”, description: “much nicer”, callback: someFunction});

If APIs like jQuery’s are any indication, this also seems to be the modern, preferred way of writing Java-Script. However, not all functions are written this way for one reason or another. In many cases it’s just a style preference, but there are situations where having to supply a list of formal parameters can be a burden. Let’s say we want to use jQuery’s super-useful $.extend() method, but we don’t know how many objects we are going to be passing into it – the amount can vary. $.extend() can take any number of objects to merge into the target object, but they must be specified as separate formal parameters, not an array.

To account for this, we could have a whole bunch of logic that would mitigate this situation – or, we can model the configuration object approach and use Function.apply() to pass the formal parameters. Function.apply(), like Function.call(), is used to modify the value of the this keyword inside of a function – the only difference is that function.apply() accepts an array that will be passed into the function as the list of formal parameters.

An array is pretty straightforward to construct and modify, much easier than accounting for an unknown amount of formal parameters. Let’s take a rudimentary example of how we might call $.extend() with an unknown amount of objects to merge in, without function.apply():

var arrayOfObjectsToMerge = [ { a: true }, { b: true }, { c: true } ], targetObj = {}, i;

// Iteratively extend() all of the objectsfor (i = 0; i < arrayOfObjectsToMerge.length; i++) { $.extend( targetObj, arrayOfObjectsToMerge[i] );}

This works, but it’s kind of ugly. And, depending on the function that we are calling, it might be inefficient, because it is getting called and running all of the function’s logic each time through the loop. If the func-tion can accept all of those parameters at once as separate formal parameters, we should supply them as such. Here’s a better way of doing it that doesn’t involve calling $.extend() repeatedly:

var arrayOfObjectsToMerge = [ { a: true }, { b: true }, { c: true } ], targetObj = {};

// Construct an array that will serve as the formal parameters$.extend.apply( $, [targetObj].concat(arrayOfObjectsToMerge) );

2/3

Page 59: Appliness #8 – November 2012

ABOUT THIS ARTICLE

Jeremy is a web developer in San Francisco. He writes front end code for YouTube and enjoys a nice Mocha. Check out his Github and some of his work he’s done in the past.

http://www.jeremyckahn.com/

@jeremyckahn

Jeremy’s Githubhttps://github.com/jeremyckahn/

Jeremy’s Bloghttp://www.jeremyckahn.com/blog/

Apply method documentationhttps://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

ONLINE RESOURCES

The last line effectively makes this call:

$.extend( targetObj, { a: true }, { b: true }, { c: true } );

The trick is to pass the method’s namespace ($, in this case) as the first parameter to Function.ap-ply(), because we don’t want to change the context of the method. We now have control over the po-tentially dynamic list of formal parameters, and we can easily feed the $.extend() method any number of formal parameters we want.

Page 60: Appliness #8 – November 2012

appliness( DON’T WORRY, BE APPLI

by Brian Ford

USING YEOMAN WITH ANGULARJSYEOMAN IS A NEW TOOL FOR SIMPLIFYING YOUR CLIENT-SIDE DEVELOPMENT WORKFLOW. IT SUP-PORTS A VARIETY OF DIFFERENT TOOLS AND FRAMEWORKS, BUT I’M GOING TO FOCUS SPECIFICALLY ON HOW IT HELPS WRITE ANGULARJS APPLICATIONS.

Out of the box, Yeoman includes some excellent features for building AngularJS apps. The best of these features is its generators. Generators allow you to quickly create new controllers, directives, services, unit tests, and even entire applications. It gives you the speed of boilerplates/seeds but with added flexibility.

Let’s look at an example. Yeoman infers the name of your project based on the name of its parent direc-tory, so let’s make a new directory and try it out:

mkdir yeoman-testcd yeoman-testyeoman init angular

Page 61: Appliness #8 – November 2012

Yeoman will report creating the following files:

.. Invoke angular ..

.. Invoke angular:app:angular ..Writing app/.htaccess...OKWriting app/404.html...OKWriting app/favicon.ico...OKWriting app/robots.txt...OKWriting app/scripts/vendor/angular.js...OKWriting app/scripts/vendor/angular.min.js...OKWriting app/styles/main.css...OKWriting Gruntfile.js...OKWriting package.json...OKWriting test/lib/angular-mocks.js...OKWriting app/scripts/yeoman-test.js...OKWriting app/index.html...OKWriting app/scripts/controllers/main.js...OKWriting app/views/main.html...OK

.. Invoke testacular:app:angular ..Writing testacular.conf.js...OK

If you’re familiar with the AngularJS seed, this project structure should look very familiar.

We can easily serve our front end with:

yeoman server

Which automatically opens your web browser, and will refresh your browser if you make changes to your application.

As you’ve probably noticed, the default generated app isn’t very interesting, but let’s look at the code. First, app/index.html

<!DOCTYPE html><!--[if lt IE 7]> <html class=”no-js lt-ie9 lt-ie8 lt-ie7”> <![endif]--><!--[if IE 7]> <html class=”no-js lt-ie9 lt-ie8”> <![endif]--><!--[if IE 8]> <html class=”no-js lt-ie9”> <![endif]--><!--[if gt IE 8]><!--> <html class=”no-js”> <!--<![endif]--> <head> <meta charset=”utf-8”/> <meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1”/> <title></title> <meta name=”description” content=””/> <meta name=”viewport” content=”width=device-width”/> <link rel=”stylesheet” href=”styles/main.css”/> </head> <body ng-app=”yeomanTestApp”> <!--[if lt IE 7]> <p class=”chromeframe”>You are using an outdated browser. <a href=”http://browsehappy.com/”>Upgrade your browser today</a> or <a href=”http://www.google.com/chromeframe/?redirect=true”>install Google Chrome Frame</a> to better experience this site.</p> <![endif]-->

2/6

Page 62: Appliness #8 – November 2012

<!-- Add your site or application content here --> <div class=”container” ng-view></div> <script src=”scripts/vendor/angular.js”></script> <!-- build:js scripts/scripts.js --> <script src=”scripts/yeoman-test.js”></script> <script src=”scripts/controllers/main.js”></script> <!-- endbuild --> <!-- Google Analytics: change UA-XXXXX-X to be your site’s ID. --> <script> var _gaq=[[‘_setAccount’,’UA-XXXXX-X’],[‘_trackPageview’]]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; g.src=(‘https:’==location.protocol?’//ssl’:’//www’)+’.google-analytics.com/ga.js’; s.parentNode.insertBefore(g,s)}(document,’script’)); </script> </body></html>

Based on the HTML5 Boilerplate, this index file also includes an ngView and the script files needed by our application. Notice that the script file is named yeoman-test.js. This is because, as mentioned before, Yeoman infers the name of your project based on the name of its parent directory.

Let’s take a look at yeoman-test.js:

‘use strict’; var yeomanTestApp = angular.module(‘yeomanTestApp’, []) .config([‘$routeProvider’, function($routeProvider) { $routeProvider .when(‘/’, { templateUrl: ‘views/main.html’, controller: ‘MainCtrl’ }) .otherwise({ redirectTo: ‘/’ }); }]);

This creates our application-level module, then provides some basic routing. Notice that there is one view defined: views/main.html. For the sake of completion, let’s take a look at this view, and its cor-responding controller:

<div class=”hero-unit”> <h1>Cheerio!</h1> <p>You now have</p> <ul> <li ng-repeat=”thing in awesomeThings”>{{thing}}</li> </ul> <p>installed.</p> <h3>Enjoy coding! - Yeoman</h3></div>

3/6

Page 63: Appliness #8 – November 2012

And here’s controllers/main.js:

‘use strict’; yeomanTestApp.controller(‘MainCtrl’, function($scope) { $scope.awesomeThings = [ ‘HTML5 Boilerplate’, ‘AngularJS’, ‘Testacular’ ];});

Again, not very interesting; the controller just publishes the list of awesomeThings onto the scope and the view makes an unsorted list from them.

But let’s say we want to make a seperate view/controller and corresponding route for adding a new item to the list of awesomeThings. Normally, you’d have to make these two files, include their script tags into your index.html, and then rewrite your route configuration. With Yeoman, you can accomplish all of that with a single command:

yeoman init angular:route add

This will tell Yeoman to generate all the files we need for a route called “add.” Enter this command and take a look at the output:

.. Invoke angular:route ..

.. Invoke angular:controller:route ..Writing app/scripts/controllers/add.js...OKWriting test/spec/controllers/add.js...OK

.. Invoke angular:view:route ..Writing app/views/add.html...OK

Invoking angular:route also invoked angular:controller and angular:view. You can actually run either of these seperatly as well, in which case they will not modify yeoman-test.js to add a route. Also note that angular:controller added two files: the controller implementation in app/scripts/con-trollers/add.js as well as a unit spec in test/spec/controllers/add.js. We’ll talk about test-ing more in a bit, but for now, let’s see what the script block of index.html looks like now:

<!-- build:js scripts/scripts.js --><script src=”scripts/yeoman-test.js”></script><script src=”scripts/controllers/main.js”></script><script src=”scripts/controllers/add.js”></script><!-- endbuild -->

It added the script tag, just as expected. Let’s check yeoman-test.js to make sure all is well there:

‘use strict’; var yeomanTestApp = angular.module(‘yeomanTestApp’, []) .config([‘$routeProvider’, function($routeProvider) { $routeProvider .when(‘/’, { templateUrl: ‘views/main.html’, controller: ‘MainCtrl’ 4/

6

Page 64: Appliness #8 – November 2012

}) .when(‘/add’, { templateUrl: ‘views/add.html’, controller: ‘AddCtrl’ }) .otherwise({ redirectTo: ‘/’ }); }]);

Yep, we have a new route.

It’s worth noting that Yeoman isn’t rewriting these files; it carefully edits them in a non-destructive way. This means that you can create your own routes, add your own files, and still use Yeoman without fear that it’s going to screw up your custom configurations somehow (but you’re using source control anyway, so that wouldn’t matter, right? ;P).

TESTING

Testing with AngularJS is already easy, but Yeoman makes it even easier still. When you use Yeoman to generate a file for you, it will also generate a stubbed out Jasmine unit test for Testacular as well. Notice when we made a new route above, it created a unit spec as well. Let’s open test/spec/controllers/main.js and see what it looks like:

‘use strict’; describe(‘Controller: MainCtrl’, function() { // load the controller’s module beforeEach(module(‘yeomanTestApp’)); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function($controller) { scope = {}; MainCtrl = $controller(‘MainCtrl’, { $scope: scope }); })); it(‘should attach a list of awesomeThings to the scope’, function() { expect(scope.awesomeThings.length).toBe(3); });});

Yeoman has created all of the boilerplate setup and teardown that a controller test would need. From here, you can easily add more tests by adding additional it and describe statements. For more on test-ing with Testacular, I recommend watching my colleague Vojta Jina’s excellent screencast.

If you haven’t yet installed Testacular, you can get it through NPM accordingly:

npm install -g testacular

5/6

Page 65: Appliness #8 – November 2012

ABOUT THIS ARTICLE

Brian Ford is a student at the University of Michigan and hacks on the web in his free time. His current interests are all things JavaScript, but most notably Node.js. He’s currently interning at Google to work on AngularJS. http://briantford.com/

@briantford

Yeomanhttp://yeoman.io/

Angular JShttp://angularjs.org/

Angular JS Seed on Githubhttps://github.com/angular/angular-seed

ONLINE RESOURCES

You can run the test as you usually would with Testacular, like this:

testacular start

This will run Testacular in “watch mode” and have it automatically run the tests whenever you update the files. Alternatively, you can do a single run through Yeoman like this:

yeoman test

which is just an alias for:

testacular start --single-run

All of the typical pains of setting up the test runner and configuring it are taken care of by Yeoman. Tes-tacular makes cross browser testing a breeze (just add additional browsers to your config file), and Angu-larJS gives you a clear seperation of concerns so you can write concise, focused tests. With these great tools, there’s really no excuse not to unit test your code.

BUILDING

To build the production-ready version of your app, simply run:

yeoman build

Yeoman will automatically concatinate the scripts between <!-- build:js scripts/scripts.js --> and <!-- endbuild -->, version the file names, and update the references to the versioned files in your html. Automatic minification is not yet implemented, but it’s coming soon!

Yeoman can also be configured to optimize images and do whatever else your application needs to be blazing fast. The build system is based on Grunt, which has many additional plugins and is highly exten-sible.

CONCLUSION

There’s a lot more to Yeoman, so if you’re interested, you should definitely check out the documenta-tion. Have ideas to improve the Yeoman AngularJS code generators? Check out the Yeoman Generator Github repo and get hacking!

Page 66: Appliness #8 – November 2012

PHOTO BY: Elle Osmani

A D D YOSMANITHE MODERN YEOMAN

PHOTOS BY: Elle Osmani

Page 67: Appliness #8 – November 2012

PHOTO BY: Umesh Nair

HI ADDY! THANK YOU FOR TAKING TIME TO SPEND WITH US. IT IS A GREAT HONOR TO HAVE YOU FEATURED IN APPLINESS. CAN YOU TAKE A MOMENT TO INTRODUCE YOURSELF TO OUR READERS?

I’m a Developer Programs Engineer on the Chrome team. That covers a lot, but I’m currently focusing on two main areas: helping developers build compelling web apps more easily and writing new documenta-tion for the Chrome Developer Tools. We have a number of powerful features being worked on in both Chrome and the tools each week and I want to empower developers to use them as soon as they’re avail-able.

Coming from a background as a JavaScript developer, I try to use my experience from the trenches to help educate others about solving pain-points in their development process. My hope is that through open-source, articles and screencasts I can help front-end developers avoid some of the common pitfalls they might run into. I get a lot of satisfaction out of the idea that we can help developers build better apps and sites.

I also enjoy skiing, mountain-biking and running. Okay. That’s a lie. I’m a developer. We only run when someone’s waving free pizza at us.

WHAT IS YOUR VISION OF A “KICK-ASS UTILITY BELT”? IS THIS AVAILABLE TODAY?

My vision of the “kick-ass” utility belt is a toolset which automates as much of your day-to-day develop-ment workflow as possible. I think you should be able to go from thinking up a concept to having a func-tional prototype ready in less than 10 or 20 minutes. That would be neat, right? At the moment, if you take time out to study the actions you perform whenever you’re writing an application, you’re likely to find that some (if not many) of them are very repetitive. Why aren’t we automating more of this?

Here is a typical workflow: We fetch libraries and frameworks, use or write boilerplate and framework-specific code, throw together unit tests and finally have to put together a build process. If that sounds at all cumbersome, consider that there’s a lot more a “modern” application developer will want to do (and use) and it can quickly become a headache to manage.

2/10

Page 68: Appliness #8 – November 2012

PHO

TO BY

: Um

esh

Na

ir

A great utility belt would give you the ability to just focus on writing the logic for your application and try to take care of the rest for you. Do I think this exists today? We’re getting closer. We’ve seen some really good tools try to address these concerns over the past few years. CodeKit, Brunch, LiveReload...all of these efforts try to help automate parts of the developer workflow and they do this well in their own ways.

They are, however, missing solutions for some key areas, like package management, build process and more flexible scaffolding. We try to address this in a project we created called Yeoman, which I’ll talk about a little more about later. It basically tries to improve the developer workflow for those working on applications as much as possible.

YOU HAVE CONTRIBUTED TO IMPORTANT IMPORTANT PROJECTS SUCH AS MODERNIZR, JQUERY, BACKBONE.JS AND CREATED SEVERAL MORE SUCH AS TODOMVC, JQUERY UI BOOTSTRAP, AURA, JQUERY PLUGIN PATTERNS AND BACKBONE PAGINATOR AS WELL AS WRITTEN BOOKS AND MANY OTHER IMPORTANT WRITINGS. FIRSTLY, HOW DO YOU DO IT ALL? SECONDLY, AS A DEVELOPER, HOW IMPORTANT IS IT TO STAY CURRENT AND ACTIVE WITH THE LATEST TOOLS? WHAT IS A GOOD WAY TO DO THIS?

Finding time for open-source is always an interesting challenge. In earlier years I would stay up late, sleeping fewer hours so that I could write articles and hack on projects. That’s more feasible when you’re young or a freelancer, but it’s not always sustainable when you have a 9-5 job or a family. I later switched to contributing during my lunch breaks at work and I found that surprisingly effective.

An hour is enough time to grab some food, write a patch and review some tickets on a bug tracker. If you’re interested in learning how something works, trying to implement it yourself in that hour (or just studying it’s source) is also a fantastic way to grasp the fundamentals. I recently showed one of my work-shop classes how to write their own version of Backbone.js in about that much time. You’d be surprised how many left understanding how it worked under the covers and it didn’t take long at all.

I believe if you really want to achieve something, you’ll make a way to find time for it. That might mean working on it a little each day, but it can be worth it in the long-term.

It also sounds like I’ve done a lot, but I certainly don’t feel that I’ve contributed to open-source as much as others have. TodoMVC, Aura, Paginator and my other open-source projects were created out of needs I had while I was writing apps over the years. With jQuery I was involved in bug triage and writing docu-mentation, Modernizr was writing feature detection tests and Backbone.js was rewriting their main demo application. Anything else, like polyfills or utilities has been out of a desire to learn.

CAN YOU TELL US A BIT ABOUT YEOMAN? WHAT WAS THE MOTIVATION FOR CREATING IT? WHAT VOID DOES IT FILL? WHAT IS UNIQUE ABOUT IT?

Sure thing. So, we were just talking about workflow.

We’re fortunate to have a wealth of helpful tools at our dis-posal on the front-end these days - tools that save us time and make our lives just a little bit easier. Abstractions like SASS and CoffeeScript, frameworks like Twitter Bootstrap, module loaders like RequireJS, a never-ending list of MVC and unit testing libraries...some would say we’re spoiled for choice and it’s interesting seeing how long it can take you to get a project started up.

As much as these tools work exceptionally well on their own, it can be a tedious process getting them to work to-gether, especially if you have to put together a workflow and build process where they all compile and get opti- 3/

10

Page 69: Appliness #8 – November 2012

PHOTO BY: Umesh Nair

mized in harmony. Even if you do manage to get a solid build process in place, you’re often left having to spend a great deal of time writing out the boilerplate code for your application.

Even then, you have to ask yourself how well this fits in with your day to day workflow. There are several little steps we repetitively do while developing which can more easily be handed off to tooling. Are you still manually refreshing your browser whenever you make a change to your app to preview how they look? Still trying to figure out whether you’re using the latest versions of all your dependencies? Wonder-ing if there was just something that let you get on with coding and forget about a lot of the grunt work?

We were too, which is why we started looking at whether we could give developers a solution to many of these common problems. We tried solving them in a free, open-source project we recently released called Yeoman. Yeoman’s official tagline is that we’re a “robust and opinionated client-side stack, com-prised of tools and frameworks that can help developers quickly build compelling web applications”.

Practically, we’re a series of tools and tasks that help you achieve automate some of the more tedious tasks in front-end development. We’re build on top of Ben Alman’s excellent Grunt.js build tool, provide easier access to package management for the front-end (via Twitter Bower) and give you a complete scaf-folding system for creating apps that we ported over from Rails.

If you find that you’re still writing boilerplate code for your application, manually managing the depen-dencies for your apps or putting together your own build system to work with the tools you love, you might find Yeoman a nice way to save yourself some headache. It’s not a silver bullet at all, but we think it’s one step further towards the ideal utility belt we discussed earlier.

4/10

Page 70: Appliness #8 – November 2012

PHO

TO BY

: Ben

Ma

rgo

lin

WHAT IS “OPINIONATED WORKFLOW”?

Good question. So, let’s talk about opinionated software for a moment. We currently work in tooling eco-systems with a lot of options. Just look at CSS pre-processors - SASS, LESS, Compass, Stylus. The list goes on.

Developers can find it hard to figure out which ones are the best to use and it’s easy to spend a long time evaluating what might be considered the most mature or most optimal. Opinionated software suggests specific options you should use that it considers best practice.

So, in Yeoman an opinionated workflow is a very similar concept. We realized that front-end developers often feel overwhelmed with the choices available and so we suggest a workflow of tools and choices that we think work well together, based on our experience with them.

Some of our opinionated choices include using Compass as your pre-processor, RequireJS for module loading and Mocha for your unit-testing needs. That doesn’t mean we just include them, but that our workflow includes a few special tooling helpers that make working with them more straight-forward.

IS IT POSSIBLE FOR DEVELOPERS TO CUSTOMIZE YEOMAN FOR THE TOOLS AND PLUGINS THEY USE?

Absolutely. Yeoman is built on top of Grunt and developers are free to customize the workflow further with tasks to suit their own needs. Admittedly, this has been a little tricky in the past, but for those want-ing more flexibility with our project, I have some good news to share.

We’re now working with the Grunt team to make Yeoman even more modular. Yeoman will be upstream-ing some of our tasks so that the rest of the Grunt (build tool) community can benefit from them. We’re also considering making our scaffolding tools completely independent so that even if you decide Grunt and Yeoman aren’t for you, you can still save a lot of time writing boilerplate code by having it do the work for you.

Imagine being able to start off a brand new AngularJS or Backbone project complete with mock unit tests and a fully customized workflow for that type of project in un-der a minute. We want you to have that.

WHAT WAS THE INSPIRATION BEHIND DEVELOPING TODOMVC?

About two years ago, we started to see a renaissance in the JavaScript community with developers starting to re-ally care about their application structure and how they organized their front-ends. There had been efforts in the past that tried to help with this problem (Dojo probably being one of the best) but developers were looking for something more lightweight with a lower barrier of entry.

This is roughly when we began to see solutions like Back-bone.js, SproutCore (now Ember), and Java-ScriptMVC start to appear and slowly gain popularity. Each solution was approaching architecture in a slightly different way with some adopting variations of the MVC patterns, oth-ers MVVM or their own derivatives. Whilst there were varying levels of documentation available for these frame-works, I still found it hard to compare them and visually (i.e., in code form) see what they were doing differently in a complete app.

5/10

Page 71: Appliness #8 – November 2012

PHOTO BY: Ben Margolin

I noticed that Backbone.js had a simple, but very easy to follow demo application (a Todo app by Jérôme Gravel-Niquet) and wondered what it would be like if I started to implement a similar app in all of these MV* frameworks. I figured that if they all did the same thing, and were structured similarly, that you could compare syntax, components and patterns and decide whether there was enough in there that you liked to warrant investing the framework further.

With time, I started to see new MVC frameworks appearing every other week and would implement an-other Todo app using them (or try to reach out to the community to help contribute one) to add to the collection. It was hard work. You had to learn a new framework, try to reach out to the people who wrote it to make sure you weren’t making a mess and get something out, usually in your lunch break.

The project started to gain attention and I decided to formalize the apps into what is now known as TodoMVC. Since then, Sindre Sorhus (a JavaScript ninja from Norway) joined the project and he’s been amazing. He helped me write an application specification for the apps and worked on rewriting them to be consistent. We now have over 40 actively developed apps, receive many requests to include new frameworks weekly and have been called the Rosetta Stone of the JavaScript MVC community.

That’s an absolute honor for a project for a project I started off during a lunch break.

MVC IS A VERY POPULAR AND COMMONLY USED PATTERN FOR FRONT-END APPLICATIONS. ARE THERE ANY OTHER PATTERNS THAT MAY BE BETTER IN CERTAIN CIRCUMSTANCES?

There’s certainly no shortage of patterns for application architecture. Some developers find that MVVM (Model View ViewModel) better suit their needs and frameworks like Knockout.js implement it well.

MVVM is a pattern based on MVC, which attempts to more clearly separate the development of user-interfaces (UI) from that of the business logic and behaviour in an application. Many implementations of it make use of declarative data bindings to allow a separation of work on Views from other layers.

The idea is that this allows UI and development work occurring almost simultaneously within the same codebase. UI developers write bindings to the ViewModel within their document markup (HTML), where

the Model and ViewModel are maintained by developers working on the logic for the application. It can be fun.

HOW CAN DEVELOPERS KEEP INNOVATING WHILE SUFFERING FROM YAFS (YET ANOTHER FRAMEWORK SYNDROME)?

Sure. So, let’s back up and talk about what YAFS means.

We refer to the current state of new (but not particularly innovative) JavaScript frameworks popping each week up as ‘Yet Another Framework Syndrome’. Whilst innovation is, of course, something we should all welcome, YAFS can lead to a

great deal of confusion and frustration in the community because there’s a great risk of it introducing more noise.

Developers often just want to start writing an app but don’t want to manually evaluate 100 different options in or-der to select something maintainable. Ask yourself

h o w many results pop-up if you’re looking for an MVC framework, a lightbox pl-

ugin or a Publish/Subscribe library and you’ll see what I mean. It sometimes feels like

trying to find a needle in a haystack.

Everyone has a different opinion about how apps should be structured, how libraries or tools should be ap-

proached and so on, so how do we solve this prob-lem? Well, I recommend a few steps:

6/10

Page 72: Appliness #8 – November 2012

1. Research. Investigate whether there aren’t already strong options developers already have in the market for the project you’re considering open-sourcing (or working on). Is it possible for you to help improve an existing project rather than creating a brand new one?

In my opinion, you should only release your project if you think it’s going to bring something uniquely better to the table. Why not speak to developers involved in similar projects early on to see what they think of your ideas?

They may have input that can help you improve these or save you time in case you’re told someone has already implemented the idea, you just didn’t find it earlier. Involving others in the community early on is always a good thing. Twitter. GitHub gists. Groups. There are plenty of channels for getting feedback early on and you should use them.

2. Document. If you go ahead with your project, make sure you document the heck out of what you do release. At TodoMVC, we currently get pull requests for a new MVC framework a few times a week and you would be surprised how many people consider documentation an optional after-thought. It’s not! Documentation is one of those things that can help make the difference between someone using your project and simply skipping over it.

3. Support. If there are 100 libraries available for achieving one task and only 3 of them are actively maintained with support available (via some channel), developers are going to ignore the other 97 in many cases. Part of open-source is making sure you do your users the service of either maintaining what you put out there, or if you’re unable to do this, saying upfront that this is the case. Your users will thank you in the long-run.

7/10

Page 73: Appliness #8 – November 2012

PHOTO BY: Umesh Nair

DO YOU HAVE A PROCESS FOR SELECTING A NEW PLUGIN OR FRAMEWORK TO USE IN YOUR PROJECTS?

When I’m selecting a new plugin or library I look for a few things. Quality is the first - I need to ensure the authors care about writing clean, readable, maintainable code that I can easily change myself later on. Next is compatibility - this can cover everything from browser compatibility (less of an issue these days) through to compatibility with dependencies. I generally try to make sure if I’m using a jQuery plugin that it’s using a version of jQuery released in the last 6-8 months. If it isn’t, I may run into upgrade issues in the future and I’d rather not have to deal with that. Using up-to-date dependencies always helps.

Next up is reliability. If I’m using a third-party library or plugin in a production environment I want to make sure it’s got unit tests. That’s a safety blanket. It tells me the author cares enough about the stability of their code to regularly test it (and any changes introduced to it) and it helps me feel more confident about using it. After reliability is performance. If you’re doing anything non-trivial with a plugin or library, you might want to benchmark it against others to see how well it compares. No one wants the libraries they include in their apps to be the bottleneck stopping them from being fast and responsive.

Lastly, I care about documentation and the likelihood of a project being maintained. I try to make sure the project has documented their APIs as well as possible. What methods and options does it support? Does it have any gotchas that users need to be aware of? I need to be able to figure out how what they’ve cre-ated works. The other side to this is support. There are times when you can learn a library or plugin well enough to maintain a version you use yourself whilst as others it just isn’t practical. When this is the case, I make sure what I’m choosing is being actively maintained and the authors are being responsive to issues the community posts on their bug tracker (or group).

Fingers crossed that criteria isn’t too picky!

IN WHICH AREAS DO JAVASCRIPT FRAMEWORKS NOT MEET THE NEEDS OF DEVELOPERS? WHAT ARE SOME ALTERNATIVES IN THESE CASES?

So, Christian Heillmann (yes, that crazy German guy with the red hair) has recently been talking a lot about looking at web development without the overhead of libraries and dependencies. Although there are cases where they’ve very much needed, he has a good point. Libraries will always add weight to your

8/10

Page 74: Appliness #8 – November 2012

page and they’re not always needed today. Why? Well, there’s been a great deal of work put into improv-ing the web platform over the past few years to better capture the needs of JavaScript developers. What you can do inside the browser these days is actually pretty amazing.

Take jQuery - fantastic DOM manipulation library which helped abstract away a lot of the cross-browser inconsistencies we used to all have to deal with. It’s really useful. If you really don’t think your users are going to have a cached version of jQuery downloaded from a CDN, you could simply use what’s available in the browser instead. Looking to run some functions when the DOM is loaded? You can use DOMCon-tentLoaded. Want to find elements in the DOM? querySelector and querySelectorAll have your back. Need to do more with classes (e.g., removing them?) you can use classList. That said, I think developers need to be careful about not re-inventing the wheel. You don’t want to rewrite jQuery - if your use case finds it too large, but you need more than just DOM manipulation, use Zepto.

It’s true that libraries aren’t always going to solve every problem and they do have an implicit cost to us-ing them, but make sure you’re spending time solving the right problems. DOM manipulation might not be what’s holding your app back. It might be performance on mobile, offline, syncing...the list of larger challenges goes on so make sure if you are trying to replace frameworks with native that it’s not going to cost time you could be spending on more important issues.

YOU’VE DONE A LOT OF WRITING AND HAVE PUBLISHED A COUPLE BOOKS. CAN YOU TELL US ABOUT THOSE AND WHERE WE CAN FIND THEM?

Sure. So, over the past two years, I’ve been working on two books - ‘Learning JavaScript Design Patterns’ and ‘Developing Backbone.js Applications’. They’re respectively about unravelling the design patterns developers often use in JavaScript these days and how to create structured apps with Backbone.js. Both of them started off as open-source projects and are available for free online so that anyone can go pick them up and start reading them. The books are also available for purchase via O’Reilly if you’d prefer to grab them in eBook or physical form or just want to support the projects.

So...why open-source? Well, maybe it’s silly but I’m a believer in educational material being readily avail-able to everybody. I know. That’s idealistic and there are certainly many more talented authors than my-self that rely on the income streams generated from selling publications. I just feel that there’s a lot of locked-down knowledge out there and I’d like to do my part in helping us evolve how we approach releasing books in our industry. Both of my books have had a few hundred thousand views each since release and although they certainly aren’t perfect, my hope is that they help developers out in some way. This is especially important in developing countries where people just can’t afford to pay the full price of a new book.

With so much material being available (freely) in blog form, I feel like we can do a better job of bal-ancing what we offer openly in book form whilst still getting something out of it ourselves.

DO YOU HAVE ANY UPCOMING PROJECTS THAT YOU ARE REALLY EXCITED ABOUT?

I’m excited about the next phase of TodoMVC, an evolution of the project we’re calling TasteJS. We re-alized that beyond MVC libraries there’s a whole world of other problems that we can help developers with.

Most of us have been in that position where we’ve been told to consider using a different stack (Rails, Node, PHP) or a special extension library for our client-side apps. Imagine if we could make it was easy to compare those as we have with TodoMVC. Utility frameworks, templating libraries...there’s a whole host of solutions we can help developers compare more easily and we’re looking at the areas where our

“I get a lot of satisfac-tion out of the idea that we can help developers build better apps and

sites.”9/

10

Page 75: Appliness #8 – November 2012

efforts can offer the most help.

TodoMVC is also going to be getting more love. We’re also starting to work with framework authors on defining a more complex application we can help developers compare. A Todo app is great, but it has quite a few limitations. It doesn’t cover session handling or authentication nor nested views or mobile. We want to come up with an app specification that addresses the needs of developers building serious applications. Maybe a social networking client or a contact list manager.

WHAT WELL WISHES WOULD YOU LIKE TO IMPART ON OUR READERS FOR A SUCCESSFUL FUTURE?

Never stop learning. I think that’s important. The best developers care about continuous improvement and they’re picking up new nuggets of knowledge everyday. Having the discipline to invest time and ef-fort in improving your craft will help you stay sharp and a few steps ahead of the curve. Other than that, work hard and always do your best and success will follow. I believe it was the British journalist David Frost who framed this quite well. He said,

“Don’t aim for success if you want it;just do what you love and believe in, and it will come naturally.”

He was right.

10/1

0

Page 76: Appliness #8 – November 2012

appliness( CHEAT SHEET

by David Walsh

5 HTML5 APIS YOU DIDN’T KNOW EXISTEDWHEN YOU SAY OR READ “HTML5”, YOU HALF EXPECT EXOTIC DANCERS AND UNICORNS TO WALK INTO THE ROOM TO THE TUNE OF “I’M SEXY AND I KNOW IT.” CAN YOU BLAME US THOUGH? WE WATCHED THE FUNDAMENTAL APIS STAGNATE FOR SO LONG THAT A BASIC FEATURE ADDITION LIKE PLACEHOLDER MADE US “TAKE A MINUTE.” DESPITE MANY HTML5 FEATURES BEING IMPLEMENTED IN MODERN BROWSERS, MANY DEVELOPERS ARE UNAWARE OF SOME OF THE SMALLER, USEFUL APIS AVAILABLE TO US. THIS ARTICLE EXPOSES THOSE APIS AND WAS WRITTEN TO ENCOURAGE YOU TO EX-PLORE THE LESSOR KNOWN HTML5 APIS!

<<

< Y

OU

CA

N S

CR

OLL

DO

WN

AN

D A

CR

OSS

TH

E C

ON

TEN

T O

F TH

IS F

RA

ME

>>

><

<<

YO

U C

AN

SC

RO

LL D

OW

N A

ND

AC

RO

SS T

HE

CO

NTE

NT

OF

THIS

FR

AM

E >

>>

Page 77: Appliness #8 – November 2012

ABOUT THIS ARTICLE

David Walsh is a 29 year old Front-End Developer in Madison, Wisconsin. He is a Web Developer for Mozilla, the ever-innovating open source organi-zation that brought you Firefox and Thunderbird. He is Founder and Lead Developer for Wynq Web Labs, core developer for the MooTools JavaS-cript Framework and Founder of Script and Style. http://davidwalsh.name

@davidwalshblog

Mozillahttp://www.mozilla.org/en-US/

MooTools JavaScript Frameworkhttp://mootools.net/

Script & Stylehttps://twitter.com/scriptandstyle

ONLINE RESOURCES

Admittedly the autofocus element is disorienting for the visually impaired, but on simple search pages, it’s the perfect addition.

Browser support for each API differs, so use feature detection before using each API. Take a few mo-ments to read the detailed posts on each feature above -- you’ll learn a lot and hopefully get a chance to tinker with each API!

RELATED POSTS

•HTML5 download Attribute

•Using HTML5 Web Storage

•Style Scavenger: 7 CSS Snippets to Borrow from HTML5 Boilerplate

•HTML5: Wrap Block-Level Elements with A’s

•HTML5 Context Menus

FEATURE

http://davidwalsh.name/templated

Page 78: Appliness #8 – November 2012

appliness( LIBRARY OF THE MONTH

by Lakshan Perera

EMBRACE THE STATIC WEB WITH PUNCHDISCOVER THIS PROJECT TO GENERATE STATIC WEB FILES.

THE STATIC WEB

Remember the very first web sites we created? It was just bunch of HTML files that we uploaded to a re-mote host using our favorite FTP program. It was all static and it just worked. Yet it was boring. Visitors wanted sites that surprised them every time they hit refresh. Moreover, we also got tired by the slow and cumbersome process we had to follow every time to update the site. Editing content within a HTML tag soup was a chaos. We broke the sites because we forgot to close some nested tag.

Along with the popularity of the LAMP (Linux, Apache, MySQL and PHP) stack, came the Content Man-agement Systems. They seemed to be the right way to manage a web site and it didn’t take long to be-come the de facto. CMSs allowed us to separate the content from the presentation and update our sites with just couple of mouse clicks. Anyone could run a site, even without knowing HTML.

However, as our sites grow and starts attracting more traffic, we see the shortcomings of CMSs. They be-come slow because they render the pages for each request. You need to tune the database and servers to handle the load. To add a trivial new feature to the site you need to modify the internals of the CMS (which is often a spaghetti code). Further,they are full of vulnerabilities. Remember the day your site got hacked, because you missed one of those daily security updates? Managing a web site seems to take up your life and become a chore.

On times like this, we start to feel nostalgic about the static web sites we created. “It was just bunch of HTML files. But it worked!”.

This inspired me to write Punch, which brings back the simplicity of static web, along with the conveniences of content management. There’s no serv-er-side code to run, no databases to configure, no mix up between HTML

Page 79: Appliness #8 – November 2012

and the content. You can resort to your favorite tools to create the site locally, preview it in the browser and finally publish the changes to any remote host using a simple command-line interface.

It’s better to understand the concepts of Punch with a simple real-life example. Let’s create a site using Punch to share your favorite books with others. We shall call this project as the “Reading List”.

If you are in a hurry, you can check the final result from here and download the source code from GitHub.

INSTALLING PUNCH

Before we start the tutorial, let’s install Punch. To run Punch you will need Node.js. Make sure you have installed Node.js (version 0.8+) on your machine. Then open up your Terminal and type:

npm install -g punch

This will install Punch as a global package, allowing you to use it as a shell command. Enter the command punch -v to check whether Punch was installed properly. This tutorial was created using Punch version 0.4.17.

SETUP A NEW SITE

Let’s spin off a new project for our Reading List. By running the command punch setup, you can create the project structure with essential files.

punch setup reading_list

This will create a directory named reading_list. Inside it we will see another two directories named tem-plates and contents. Also, you will find a file named config.json. You will learn the purpose and role of these directories and files as the tutorial progress.

While we are inside the project directory, let’s start the Punch server by running the command:

punch s

This will allow us to preview the site we create in real-time. By default, the server starts on the port 9009.

Open your browser and enter the URL http://localhost:9009. You should see the welcome screen along with a link to a quick hands-on tutorial. I highly recommend you to take couple of minutes to go through this quick tutorial first, which will help you to grasp the core concepts of Punch. I’ll wait till you finish it.

2/7

Page 80: Appliness #8 – November 2012

PREPARING THE LAYOUT

In the quick hands-on tutorial, you learnt Punch uses Mustache as the default templating language. Also, you learnt the layouts, partials and static assets that composes a site’s user interface must be saved inside the templates directory.

Make sure you removed the {{{first_run}}} from the templates/_footer.mustache to get a clean view sans the hands-on tutorial.

Now let’s turn our focus back to the Reading List page we are creating. It should contain the following information:

- Introduction

- List of Books (we must provide the following information for each book)

- Title

- Cover image

- Author

- ISBN

- Your rating

- Favorite quote from the book

- Link to the book in Amazon

We only need to create a single web page to show these information. So we can directly customize the default layout (templates/_layout.mustache) to create the view we need.

{{> header }}

<div role=”main”> <p>{{{intro}}}</p> <div id=”books”> {{#books_list}} <div class=”book”> <h3><a href=”{{amazon_link}}”>{{{title}}}</a></h3> <div class=”cover”><a href=”{{amazon_link}}”><img src=”{{cover_image}}”></a></div> <ul> <li><b>Author</b> - {{author}}</li> <li><b>ISBN</b> - {{isbn}}</li> <li><b>Rating</b> - {{rating}}</li> <li><b>Favorite Quote</b> - {{{favorite_quote}}}</li> </ul> </div> {{/books_list}} </div> </div>

{{> footer }}

Note that some Mustache tags are surrounded with three curly-braces, while others are surrounded with two curly-braces. By having three curly-braces we say Mustache not to escape the HTML within the con-tent. In places where you want to have HTML formatted content, you must use the tags with three curly- 3/

7

Page 81: Appliness #8 – November 2012

braces.

After modifying the layout, refresh the page in the browser to see the changes.

CREATING THE READING LIST IN JSON

Still you won’t see any visual difference in the page. But if you view the source of the page, you will see the HTML structure you defined with empty values in the places where there were Mustache tags. We must provide content to render into those tags.

Let’s start with the most essential piece of content of the page - list of books. Open the contents/index.json and start entering the details of your favorite books in the following format.

{ “book_list”: [ { “title”: “The E-Myth Revisited”, “amazon_link”: “http://www.amazon.com/gp/product/0887307280”, “cover_image”: “http://ecx.images-amazon.com/images/I/41ieA7d6CYL._SL160_.jpg”, “author”: “Michael E. Gerber”, “isbn”: “0887307280”, “rating”: “10/10”, “favorite_quote”: “\”The true product of a business is the business itself\”” } ]}

We’ve defined a JSON array named book_list which contains multiple book objects. For each book ob-ject, we define the required details as properties.

Save the file after entering the books and refresh the browser. You should now see the book list you just created rendered into the page as HTML.

You can continue to add more books or update the existing entries in the contents/index.json. The page will be rendered every time you make a change in the content.

WRITING THE INTRODUCTION TEXT USING MARKDOWN

So now we have listed our favorite books, let’s add a simple introduction to the page. Rather than defin-ing it as a JSON string, you can use Markdown formatting to write this piece.

When fetching contents for a page, Punch will look for extended contents such as Markdown formatted texts, in a directory by the name of the page prefixed with an underscore. This directory must be placed inside the contents directory along with the JSON file for the page.

In this instance, we should create a directory named _index and save our introduction inside it as intro.markdown. The filename of an extended content should be the tag name you wish to use in the templates to retrieve that content.

4/7

Page 82: Appliness #8 – November 2012

CHANGING THE SITE’S TITLE

You will notice site’s title is still displayed as “Welcome”. Let’s change that too. Site-wide content such as the site’s title, navigation items are defined in the contents/shared.json file. Open it and change the site’s title to “Reading List”.

STYLING WITH LESS

Now we are done preparing the content, let’s do some style changes to beautify the page. You can use LESS to write the styles and Punch will automatically convert them into regular CSS.

As I mentioned previously, all static assets such as stylesheets, JavaScript files and images must be stored in the templates directory. You can organize them in any way you like inside the templates directory.

You will find the default site specific styles in templates/css/site.less. Let’s change them to achieve the design we want for Reading List. To keep this tutorial concise, I won’t show the modified stylesheet here. You can check it from the project’s repo on GitHub:

Similar to processing the LESS files, Punch can also pre-compile CoffeeScript files into JavaScript auto-matically.

MINIFYING AND BUNDLING CSS/JAVASCRIPT ASSETS

Minifying and bundling of CSS & JavaScript assets are recommended performance optimizations for all kinds of web sites. Those help to reduce the number of round-trips browsers needs to make in order to fetch the required assets and also minimizes the size of the assets that needs to be downloaded.

Minifying and bundling assets in a Punch based project is fairly straightforward. You only have to define your bundles inside the config.json. Then Punch will prepare and serve the minified bundles at the time of generating the site.

We can bundle the CSS files used in the project like this:

“bundles”: { “/css/all.css”: [ “/css/normalize.css”, “/css/main.css”, “/css/site.less” ] }

Then, you can use Punch’s bundle helper tags to call defined bundles inside the templates.

<head> <!-- snip --> {{#stylesheet_bundle}}/css/all.css{{/stylesheet_bundle}} </head>

This will produce a fingerprinted stylesheet tag (useful for caching) like this:

<head> 5/7

Page 83: Appliness #8 – November 2012

<!-- snip --> <link rel=”stylesheet” type=”text/css” media=”screen” href=”/css/all-1351313179000.css”> </head>

Similar to stylesheet_bundle tag, there’s a javascript_bundle tag which you can use to call JavaScript bundles from a page.

PUBLISHING TO S3

Our Reading List page is now almost complete.

Let’s share it with others by publishing on the web. Punch allows you to either publish your site directly to Amazon S3 or upload it to a preferred host using SFTP.

In this tutorial, we will publish the site to Amazon S3. You will have to signup with Amazon Web Services and enable the S3 storage service for your account. Then, create a S3 bucket and a user who has access to bucket.

Enter those settings in the config.json file of your Punch project under the section name publish.

“publish” : { “strategy” : “s3”, “options” : { “bucket” : “BUCKET”, “key” : “KEY”, “secret” : “SECRET”, “x-amz-acl”: “public-read” } }

Then on the terminal, run the following command:

punch p

This will publish the Reading List site you just created to S3. Point your browser to the URL of your S3 bucket and you should see the site.

You can check the sample site I created by visiting this URL: http://readlist.s3-website-us-east-1.ama-zonaws.com/ 6/

7

Page 84: Appliness #8 – November 2012

In future, if you want to add a new book or update an existing entry, all you need to do is edit the list in contents/index.json and then run the command publish p. It will publish only the modified files from the last update.

EXTENDING PUNCH

In this tutorial, I covered the basic workflow for creating and publishing a site with Punch. You can easily extend and customize it further based on your requirement.

For example, you can implement your own content handler to enable sorting of the book list by different criteria. Also, if you prefer to use a different templating language than Mustache, you can write your own template engine wrapper to Punch (check out the implementation of Handlebars engine).

If you’re interested in learning more about the available features in Punch and how to extend them, you can refer the Punch Guide.

Page 85: Appliness #8 – November 2012

appliness( SHOWCASE

COMPLETURECOMPLETURE ALLOWS USERS TO LISTEN TO POLICE SCANNERS IN MORE THAN 15 COUNTRIES AND CREATE MINI-STORIES BY CAPTURING REAL-WORLD EVENTS USING CAMERA, GEOLOCATION, AND HAVE THE COMMUNITY VOTE AND SHARE THEM TO DERIVE THE TOP ONES.

“We wanted an open source technology to develop a robust application in a fast and efficient way with a small learning curve,” said Mark Malkoun, co-founder of Completure. “We also needed the ability to change fea-tures easily so we knew that HTML5 was the way to go. After we studied all the solutions out there we were amazed by the PhoneGap approach and its flexibility, especially the PhoneGap plugins and the community working on it. Phonegap is not only the best, but the only real solution to our problems.”

Decentralized - Instead of having centrally-controlled media giants de-ciding what the public should or should not know about, Completure em-powers users to share news.

It’s not like your typical followers-based social network. If an important event is happening in your area you will know about it without having to follow anyone who happens to be there.

Data is accurate and noise-free in terms of location and time, as only 3-day old + geotagged photos are accepted.

Create a story and publish in seconds. Take a series of pictures, write a few words and publish your story to shed a light on anything you want your community to know about.

“We wanted an open source technology to develop a robust application in a fast and efficient way with a small learning curve.” said Mark Malkoun, co-founder of Completure.

BUILT W

ITH PHONEGAP

Page 86: Appliness #8 – November 2012

Fresh news about HTML and Javascript collected by Brian Rinaldi - remotesynthesis.com

appliness( HELTER SKELTER NEWS

Kick-Start Your Project: A Collection of Handy CSS Snippetsvia Hugo Giraudel JavaScript Fundamen-

tals: Variablesvia Joe Zim

The Road To Reusable HTML Componentsvia Niels Matthijs

Getting Started with Web Workersvia Agraj Mangal

Javascript OO Without Constructorsvia Toby Ho

Fonts, fabulous fonts: How to use the @font-face rule with popular font servicesvia Janine Warner

Exploring the HTML5 Web Audio: visualizing soundvia Jos Dirksen

Dynamic Invocation Part 1: Methodsvia Justin Naifeh

Add Edge Animate Compositions to Re-veal.jsby Terry Ryan

Page 87: Appliness #8 – November 2012

appliness( HELTER SKELTER NEWS

MORE NEWS ON REMOTESYNTHESIS.COM

Understanding JavaS-cript OOPvia Quildreen Motta

Javascript: Function Invo-cation Patternsvia Barry Steyn

Does JavaScript need classes?via Nicholas Zakas Did a meta tag just

kill the mobile splash screen?via Anders Andersen

The Graphical Web Ex-perimentvia CJ Gammon

Gaming: Battle on the High Seas, Part 1via Jeff Friesen

Simple yet amazing CSS3 border transi-tion effectsvia Code Player

HTML5 Image crop tool without server side using javascriptvia Saravanan

Totally Testacularby Alex Young

Page 88: Appliness #8 – November 2012

CREATE THE WEB-TOUR-SA

VE TH

E DAT

E

Find out how Adobe is helping move the web forward and get a sneak peek at new tools, technologies and services for web designers and developers. Join Adobe for a series of free full-day events to learn about the latest tools and techniques for creating content for the modern web.

Topics covered include HTML, CSS, motion graphics, web development and more.

Guangzhou

November 10th

Hamburg

November 13th

Boston

November 14th

Lisbon

November 15th

REGISTER REGISTER REGISTER REGISTER

^^^SCROLL THE CONTENTS OF THIS TABLE

DATE EVENT CITY LOCATIONS REGISTER

11/10/12 Guangzhou China Register >

11/13/12 Hamburg Germany Register >

11/14/12 Boston United States Register >

11/14/12 Denver United States Register >

11/15/12 Chengdu China Register >

11/15/12 Lisbon Spain Register >

11/16/12 Toronto Canada Register >

11/17/12 Shanghai China Register >

11/29/12 Philadelphia United States Register >

12/23/12 Sao Paulo Brazil Register >

Page 89: Appliness #8 – November 2012

appliness( THE TEAM

Contribute and join ApplinessAppliness is a free digital magazine edited by passionate web developers. We are looking for contributors. Con-tact us and join the adventure. You’ll find on our website appliness.com a feedback form. You can also follow us on twitter, facebook and Google+.

M I C H A E L CHAIZE

Michaël Chaize is a Developer Evangelist at Adobe where he focuses on Rich Internet Application and Mo-bile applications. Based in Paris, he works with large accounts that need to understand the benefits of rich user interfaces, leverage the existing back-ends to add a rich presentation layer and measure the impact on the existing IT teams. He believes that intuitive user experiences in the Enterprise are key to successful de-velopments of effective, efficient, engaging, easy to learn and error free applications. Before joining Ado-be, Michael founded a software company and taught RIA languages such as Flex and PHP in IT engineering schools. He’s the editor in chief of Appliness.

P I O T R WALCZYSZYN

Piotr Walczyszyn is a technology geek living in War-saw, Poland, where he was born. out of.me is his new blog in which he wants to express his current interests and share some of his work.

Technologies change; new trends come and go. These days nobody talks about RIAs (Rich Internet Applica-tions) anymore, and he thinks this phrase has become almost passe although its main concepts have not.

PA U L HUNT

Paul has been working at Adobe Systems foundry since January 2009 helping to develop typefaces at every level of production from conceptualizing and drawing to OpenType programming, exporting and beta testing.

B R I A N RINALDI

Brian Rinaldi is as a Content and Community Man-ager for the Adobe Developer Center team, where he helps drive content strategy for HTML5 and JavaS-cript developer content.

Brian blogs regularly at http://remotesynthesis.co-mand and is a unreformed twitter addict.

D M I T R Y BARANOVSKIY

Dmitry is a Sydney-based web developer interested in HTML, CSS, JavaScript, XSLT and SVG. Currently he is working at Adobe as a Senior Computer Scientist. He’s the creator of the JavaScript library “Raphael”.

A N D R E W T R I C E

Andrew Trice is a Technical Evangelist with Adobe Systems. Andrew brings to the table more than a de-cade of experience designing, implementing, and delivering rich applications for the web, desktop, and mobile devices. He is an experienced architect, team leader, accomplished speaker, and published author, specializing in object oriented principles, mobile de-velopment, realtime data systems, GIS, and data visu-alization.

M A I L E VALENTINE

Maile is the assistant editor for Appliness magazine and has worked with Adobe both as an employee and consultant for 8 years now. Maile started with Adobe on the Technical Marketing team as a technical train-er for the Adobe LiveCycle Enterprise Suite (most re-cently Adobe Digital Enterprise Platform).

She then went on to work with the Adobe Enterprise Evangelist team to support great Flex developer re-sources such as Tour de Flex and Flex.org. Maile is excited to jump into the world of digital publishing and dig deeper into leading edge HTML and related technologies.

G R E G WILSON

Greg is a Developer Evangelist at Adobe Systems fo-cusing on the use of Adobe technologies in enterprise applications. Technologies include HTML, JavaScript and related technologies, Flex, AIR, data services, digital publishing, and anything mobile, tablet and desktop app development related. Prior to joining Adobe, Greg architected and developed many large-scale applications at Verizon, Motorola, NASA/Boe-ing and others.

CHRISTOPHE COENRAETS

Christophe is a Developer Evangelist for Adobe where he focuses on Web Standards, Mobile, and Rich HTML Applications with a special focus on Enterprise Inte-gration. In this role, Christophe has helped some of the largest financial services companies design, archi-tect and implement some of their most mission criti-cal applications. He was one of the initial members of the Flex Product Team in 2003. In his previous role at Macromedia, Christophe worked on JRun, the com-pany’s J2EE application server. Before joining Macro-media, Christophe was managing Java and Internet Applications Evangelism at Sybase and Powersoft. Christophe has been a regular speaker at conferences worldwide for the last 15 years.

H O L L Y SCHINSKY

Holly is a Developer Evangelist at Adobe Systems and has been doing software development since 1996 with experience working for various Fortune 500 compa-nies to startup. Holly’s experience is primarily in OO languages, but she thrives on constantly learning new things & is always up for a challenge.