Appliness #2 – May 2012

102
appliness ( #2 - MAY 2012 The digital magazine for web app DEVELOPERS Exclusive interview Pamela Fox TUTORIALS HTML5, BACKBONE, jQUERY, PHONEGAP, BOOTSTRAP, CSS3... HTML5 & JS PHONEGAP FILE API, MULTIMEDIA COM- PONENTS, APP-UI JS

description

It features technical tutorials for web application developers about HTML5, JavaScript, mobile development, best practices…Download it for free on the Apple app store or on the Google Play market !!!

Transcript of Appliness #2 – May 2012

  • appliness(#2 - MAY 2012

    The digital magazine for web app DEVELOPERS

    Exclusive interviewPamela Fox

    TUTORIALS

    HTML5, BACKBONE, jQUERY, PHONEGAP, BOOTSTRAP, CSS3...

    HTML5 & JS

    PHONEGAP FILE API, MULTIMEDIA COM-PONENTS, APP-UI JS

  • 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 second issue of this MAgAzine.

    TABLE OF CONTENTS

    DONT WORRY, BE APPLI

    DRAG & DROP WITH JQUERY UI by Michal Chaize

    JAvAscRIPT ObJEcT cREATIOn: lEARnInG TO lIvE WITHOUT nEW by Keith Peters

    UsInG bAckbOnE.Js WITH JQUERY mObIlE by Christophe Coenraets

    DEmO Of HAnDlEbARs, AnD WHY YOU sHOUlD cOnsIDER A TEmPlATInG EnGInE by Raymond Camden

    REAl-TImE DATA Ex-cHAnGE In HTml5 WITH WEbsOckETs by Ryan Stewart

    sWIPE TO DElETE ITEms WITH JQUERY mObIlE On TOUcH DEvIcEs by Michal Chaize

    APP-UI, A JAvAscRIPT lIbRARY by Andrew Trice

    HTml5 AnD mUlTImEDIA: vIDEO, AUDIO AnD cOmPOnEnTs by Ian Devlin

    InTERvIEW Of PAmElA fOx by Maile Valentine

    THREE GREAT PHOnEGAP APPlIcATIOns by Michal Chaize

    PUll QUOTE AnD cOmmEnTs by Terry Ryan & Ray Camden

    LIBRARY OF THE MONTH

    FOCUS GROUP

    INTERVIEW

    SHOWCASE

    WHICHELEMENT.COM

    PHOnEGAP AnD THE fIlE API by Raymond Camden

    VIDEO TUTORIAL

    DEcIsIOn PATH TO PHOnEGAP by Michal Chaize

    VISUAL AND jUICY

    fAlsE ADvERTIsInG by Toby Ho

    WTFjS

    GEnERATInG cOlOR PAlETTEs fROm HTml5 vIDEO by Raymond Camden

    BLEEDING EDGE

    css vARIAblEs DRAfT by Terry Ryan

    nEWs AbOUT HTml AnD JAvAscRIPT by Brian Rinaldi

    HELTER SKELTER NEWS

    WHOs bEHInD THE mAGAzInE by the team

    TEAM

    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

    SHAPE TOMORROW TODAY

    ExPREssInG RIcH lAY-OUTs WITH sImPlE, DEclARATIvE cssby Deepa Subramaniam

    cRAfTInG nATIvE lOOkInG IOs APPs WITH HTml by Christophe Coenraets

  • appliness( SHAPE TOMORROW TODAY

    ExPRESSING RICH LAYOUTS WITH SIMPLE, DECLARATIVE CSSAlong with the community, ADoBe engineeRS ARe Developing new StAnDARDS AnD ADvAncing exiSting StAnDARDS. in thiS ARticle, they intRoDuce cSS RegionS AnD cSS excluSionS which ARe two pRopoSAlS foR the w3c. thAnkS to theSe new ADDitionS, A DeSigneR oR DevelopeR cAn cReAte high-quAlity, mAgAzine-Style lAyoutS foR the weB uSing html5 AnD cSS3.

    A rich digitAl forMAt

    it is hard to deny that its an exciting time for innovation on the web. Some of the powerful proposals coming out of working groups in the w3c are letting designers and developers build standards-based rich content with html5, cSS3 and JavaScript in a much easier way.

    one area that is ripe for innovation is around how to better translate classic print designs to a rich digi-tal format. the reality is that several of the capabilities that are taken for granted when designing con-tent for print are still very difficult to implement using web standards. when print designs are converted to an html-based form for digital consumption, one of the current limitations is that expressive layouts do not translate well. this is an area that Adobe has a lot of experience with and a problem we want to help solve. to start, we have worked with partners to introduce two proposals to the w3c cSS working group: CSS Regions and CSS Exclusions. in addition to championing two new standards, were imple-menting these proposals directly in open browser engines like webkit. with both cSS Regions & cSS exclusions, a designer or developer can create high-quality, magazine-style layouts for the web using html5 and cSS3.

    lets first discuss cSS Regions. html and cSS today allow you to place text in a box, and has support for flowing text through identical column boxes contained in a single box. if you want to size and position

    3/7

    css regions

  • 4/7

    separate boxes for your text to flow through, you can only approximate your desired layout by breaking up your text and assigning which text goes in which box. this results in a fixed layout that breaks down at the slightest change of font or window size. with the introduction of cSS Regions, you can flow unbroken text fluidly from box to box without any restrictions on size or position. Designers & developers are free to use columns and gutters with different widths and flow text through whatever expressive layout they choose to create.

    cSS Regions makes achieving this easy. with this new feature, you can specify how text or images should flow across multiple regions with simple, declarative cSS. in the video below, three distinct regions are specified and as the browser resizes, notice how the text flows naturally from one region to the other.

    the code for this is quite simple. the text source is named using the new vendor prefixed -webkit-flow-into cSS property on the element that contains the content. this naming causes the content to be removed from the normal cSS layout flow and allows it to be inserted into specially defined regions by setting the -webkit-flow-from property. the code for the video above looks like this:

    CSS:#source{ -webkit-flow-into: main-thread;}

    .region{ -webkit-flow-from: main-thread;}

    HTML:

    lorem ipsum dolor [...]

  • 5/7

    in fact, regions can be positioned anywhere. using this same syntax, you can have multiple threads of text or images flow into separate chains of regions. the video below shows two threads of text flowing into non-contiguous regions because the order in which text is flowed is explicitly controlled by the -web-kit-flow-into property.

    here is a video of a more complex example created by Adobe engineer, christian cantrell. in this sample, a short story is formatted using cSS Regions. youll notice that the story is divided into two columns, which is more of a print-like layout and friendly to read. the power of cSS Regions becomes obvious when you see that the text is actually flowing from one column to the other. notice that as the browser resizes, the text flows from column to column and the page concept is maintained. without cSS Regions, you would have to write a fair amount of JavaScript to break the text into appropriately sized pieces (and re-run the script any time the font or window size changed). now its just a matter of setting a few cSS properties!

  • 6/7

    css eXclusions

    what is even better is that cSS Regions can be experimented with now! All of the above examples were shown in recent builds of chrome. cSS Regions is also available in the Developer preview of internet ex-plorer 10 and nightly builds of webkit. while there has been great progress, cSS Regions is still a cutting edge feature so in some cases it is protected by both vendor prefixes and runtime flags. to play with cSS Regions in chrome you will need to enable the feature through the --enable-css-regions runtime flag. there are instructions on the web about how to easily do this in chrome.

    we are thrilled with how cSS Regions is progressing and are working on some new features to add. these include making it even simpler to style regions, auto-setting the height for regions, and introducing a page template model to create boxes in cSS and better handle pagination. to stay informed of the evo-lution of cSS Regions and get access to sample code and new demos, keep an eye on the cSS Regions page on html.adobe.com.

    A complementary feature to cSS Regions is cSS exclusions, which allows the creation of custom text ex-clusions to wrap text with shapes or images. Again, with simple cSS properties, you can define a custom shape as the container for text, like so:

    or cause text to flow around a custom shape like so:

  • About this Article

    Deepa Subramaniam is the group product manager for Adobes web platform team a team focused on making the web more awe-some by collaborating with the community to champion new standards and contribut-ing to open source projects like webkit. She loves sun, coffee and good-looking code. http://html.adobe.com

    @iamdeepa

    The Adobe & HTML websitehttp://html.adobe.com

    CSS Regions W3C Specificationhttp://dev.w3.org/csswg/css3-regions/

    CSS Exlusions W3C Sepcificationhttp://dev.w3.org/csswg/css3-exclusions/

    online resources

    this behavior is simple to achieve with just a few new properties cSS exclusions introduces. the webkit-wrap-shape property defines the boundary in which to flow text content and also defines the area to be avoided when laying out content. the -webkit-wrap-shape-mode property controls how the content re-sponds to a shape and flows the content appropriately.

    in this video, using the webkit-wrap-shape and webkit-wrap-shape-mode cSS properties, you can see several things. notice that as the browser resizes, text flows around the custom shape and if the shape size changes, the text continues to flow as one would expect of a responsive layout. Additionally, the custom shape can be dynamically swapped to any polygon and text layout and reflowing capabilities are maintained!

    Adobe is actively working on cSS exclusions and while it is not yet fully available in current browsers, it should be available in chrome and webkit nightly builds soon. the cSS exclusions page on Adobe & html will be updated as the feature progresses but till then, it is there you can access a custom webkit build to play with the feature now. we think the power that both cSS Regions and cSS exclusions offer designers and developers is very exciting! expressive, liquid layouts are achievable with just a few cSS properties and a clever eye. were thrilled that the features are being used to create com-

    pelling digital experiences, like in the following example where both features are used to cause text to flow around the mountain and car images as the user scrolls the arrow to pan around.

    keep an eye out for cSS Regions and exclusions to land in your favorite browser and we hope you con-sider using them as you develop rich layouts on both desktop and mobile devices.

  • appliness( DONT WORRY, BE APPLI

    DRAG AND DROP WITH JQUERY UIDRAg AnD DRop iS A clASSic geStuRe in DeSktop ApplicAtionS. leARn how to coDe it on touch DeviceS Such AS youR tABlet uSing JqueRy ui AnD Some hAckS.

    by michal chaize

    whY use drAg And drop on A tAblet?

    As a RiA (Rich Internet Application) developer, i try to introduce meaningful and efficient user inter-actions in my apps. A classic and natural way to associate items is to use drag and drop. its a classic action in desktop applications. with the introduction of touch screens, its even more natural on mo-bile devices. when you need to order items, assign items to categories or to an action, drag-and-drop makes sense.

    in this tutorial, ill play with a list of team members and a list of tasks. As you can guess, the end-user will be able to assign a specific member to a task member using drag-and-drop. Desktop frame-works have implemented Drag and Drop management based on mouse events. thats why a lot of these libraries are not effective on touch devices. well see in this tutorial how to hack these libraries and simulate touch events.

    on the next page, you can start playing with the final application. Drag users on tasks using your fin-ger and read this tutorial to understand how to code it.

    Playground

    - jQuery

    - jQueryUI

    - CSS

    Difficulty- rookie- intermediate

    - expert

    Todo list- drag stuff- drop things- wash fingers

    8/14

  • plAY with the finAl ApplicAtion

    Some cool features that you should notice:

    - if you dont drop a user on a task, then he will automatically move back to his original place. - users snap to the edges of the task boxes while dragging them on the stage. - once a user is assigned to a task, you cannot drag him anymore, and you cannot drop another user on this task.

    enAble drAg And drop on touch devices

    there are several ways to enable drag and drop for items in a web page. for this application, i wanted to use jquery ui because it provides robust abstractions for low-level interactions and animations. its built on top of jquery, so you can easily reuse that library for your desktop and mobile apps. once you import the jqueryui library in your web project, you just need to give an id to a element and call $(#idOfMyElement).draggable(). unfortunately, jqueryui has been designed for desktop apps and mouse events.

    David furfero (furf.com) has developed a small hack that consists of mapping touch events to their mouse event analogs. it works perfectly on ioS and Android devices. he shared his code on github in a library called touch-punch for jqueryui. its160 lines of code library that can become very useful. first, David starts by detecting if the device supports touch events.

    9/14

  • // Detect touch support $.support.touch = ontouchend in document;// Ignore browsers without touch support if (!$.support.touch) { return; }

    then he gets a reference to the mouse prototype:

    var mouseProto = $.ui.mouse.prototype;

    for every touch event, he will simulate the corresponding mouse event. he rewrites the touchMove handler:

    mouseProto._touchMove = function (event) {

    // Ignore event if not handled if (!touchHandled) { return; }

    // Interaction was not a click this._touchMoved = true;

    // Simulate the mousemove event simulateMouseEvent(event, mousemove); };

    the simulateMouseEvent contains the hack and the classic event.preventDefault() call.

    function simulateMouseEvent (event, simulatedType) {

    // Ignore multi-touch events if (event.originalEvent.touches.length > 1) { return; }

    event.preventDefault();

    var touch = event.originalEvent.changedTouches[0], simulatedEvent = document.createEvent(MouseEvents); // Initialize the simulated mouse event using the touch events coordi-nates simulatedEvent.initMouseEvent( simulatedType, // type true, // bubbles true, // cancelable window, // view 1, // detail touch.screenX, // screenX touch.screenY, // screenY touch.clientX, // clientX touch.clientY, // clientY

    10/1

    4

  • false, // altKey false, // shiftKey false, // metaKey 0, // button null // relatedTarget );

    // Dispatch the simulated event to the target element event.target.dispatchEvent(simulatedEvent); }

    this touch-punch library is on github. Just download it and include it in your web project in addition to jqueryui and jquery.

    drAg...

    now you can use the draggable() plugin on your elements and start dragging them on the stage.

    Drag

    $(function() { $( #draggable1 ).draggable(); });

    DRAG ME

    11/1

    4

  • Michal C. DROP HERE Task 1

    ...And drop

    lets define a drop zone for our user. the jquery ui Droppable plugin makes the elements of your choice droppable, which means that they accept being dropped on by draggables. in this application, the element with the id droppable_1 will be our target. A drop event will be triggered when the draggable will be dropped over. in the callback, well find the paragraph element and modify the text from task 1 to task assigned.

    $(function() { $( #draggable1 ).draggable(); $(#droppable_1).droppable({ drop: function( event, ui ) { $( this ) .find( p ) .html( Task assigned) } }); });

    DRAG ME Michal C.

    12/1

    4

  • DROP HERE Task 1

    snAp Mode

    the method has some very cool built-in options. to guide the user, you can choose to snap a drag-gable to the edges of a specific element. in this case, i want the user to snap the inner edges of the task box while dragging it. in the draggable plugin options, i specify the selector as a snap tar-get and i set the to (possible values are , and ). i also want to add a visual feedback if a user is not dropped on a task (on a valid droppable element). thats why i set the option to .

    $( #draggable1 ).draggable({ snap: .ui-widget-header, snapMode: inner,revert:true });

    By default, the draggable object will always return to its original position when dropped. i need to disable the behavior when the item is dropped on a correct place. to do so, i just need to extend the drop callback setting the option to . im also setting the final coordinates of the draggable element once dropped using the options.

    $(#droppable_1).droppable({ drop: function( event, ui ) { $( this ) .find( p ) .html( Task assigned) ui.draggable.draggable(option,revert,false); ui.draggable.position({of: $( this ),my: left bottom, at: left bottom }); } });

    13/1

    4

  • disAble And stYle with css

    lastly, i need to disable the draggable and the droppable behaviors on my ele-ments. i can also set new styles using the addClass() method to change the visual appearance of my draggable item and of my task box.

    $(#droppable_1).droppable({ drop: function( event, ui ) { $( this ) .addClass( ui-state-highlight ) .droppable(disable) .find( p ) .html( Task assigned); ui.draggable.draggable(disable); ui.draggable.addClass(correct); ui.draggable.draggable(option,revert,false); ui.draggable.position({of: $( this ),my: left bot-tom, at: left bottom }); } });

    /... style.CSS .../.correct{ opacity:1; background-color:#C2FF84;}

    get the source code

    if my final application, i have four users and four tasks. using jquery loops, you can easily reproduce the techniques ive used in this tutorial. in a tasks DIV element, i have several droppable_n ele-ments (droppable_1, droppable_2), so i can use the generic iterator each() function of jquery.

    $(#tasks div).each(function(idx, item) { var idTask = parseInt(idx) + 1; $(#+item.id).droppable({ drop: function( event, ui ) { $( this ) .addClass( ui-state-highlight ) .droppable(option, disabled, true) .find( p ) .html( Task +idTask+ assigned ); ui.draggable.draggable(disable); ui.draggable.addClass(correct); ui.draggable.draggable(option,revert,false); ui.draggable.position({of: $( this ),my: left bottom, at: left bottom }); } });});

    MORE INFORMATION> >

  • appliness( DONT WORRY, BE APPLI

    JAVASCRIPT OBJECT CREATION: LEARNING TO LIVE WITHOUT NEWin thiS ARticle, im going to DiScuSS oBJect cReAtion in JAvAScRipt uSing pRototypAl inheRitAnce AS An AlteRnAtive to the new opeRAtoR.

    by keith peters

    eMbrAce the jAvAscript lAnguAge

    one significant aspect of JavaScript is that there is rarely a single right way to do any particular task. JavaScript is a loosely-typed, dynamic, and expressive language, which means that there are usually many different ways to accomplish the same task.

    im not saying that the methods described here to create objects are the only correct ways to do so or even the best ways, but i do feel that they are closer to the true nature of the language and will help you to understand whats going on under the covers if you choose to use other methods.

    to help you better understand these concepts, this article describes the creation of a basic particle system with multiple rendering targets. this is a complex enough task to represent a real world test of the concepts ill be demonstrating, rather than a simple hello world type of application.

    Playground

    - JavaScript

    - Prototype

    - Canvas

    Difficulty- rookie- intermediate

    - expert

    Todo list- forget class- code reuse- particles

    15/2

    7

  • 16/2

    7

    the crux of this article is the creation of JavaScript objects. most tutorials you see will tell you to create a constructor function, add methods to the functions prototype property, and then use the new opera-tor like so:

    function Foo() { this.name = foo;}Foo.prototype.sayHello = function() { alert(hello from + this.name);};var myFoo = new Foo();myFoo.sayHello();

    the newly created object now has all the properties that were defined on the constructor functions pro-totype. this creates something that looks much like a class in a class-based language. to make a new subclass that inherits from that class, youd set the prototype property of the subclass to a new in-stance of the original class. (im using quotation marks here because the entities are not actual classes or subclasses.)

    function Bar() {}Bar.prototype = new Foo();

    Bar.prototype.sayGoodbye = function() { alert(goodbye from + this.name);}var myBar = new Bar();myBar.sayHello();myBar.sayGoodbye();

    the problem is that because this structure looks so similar to real classes in other languages, people start expecting it to behave exactly like real classes behave in other languages. But the more you work with these types of classes, the more you see that they dont behave that way at all. So people get upset with JavaScript, and start thinking it is a bad language that cant be used for anything serious. others go about trying to fix these class-like structures, tacking on various bits of functionality and building up very complex frameworks to get constructor functions and prototypes to look and behave more and more like classes.

    personally, i see this as a bit of a misguided effort. its not necessarily wrong, but the energy being spent would likely produce better results if it was in another direction.

    JavaScript is not a class-based language, but a prototype-based one. code reuse is done not by making class templates that are used to instantiate objects, but by creating new objects directly, and then mak-ing other new objects based on existing ones. the existing object is assigned as the prototype of the new object and then new behavior can be added to the new object. its quite an elegant system and its beautifully implemented in the io language, which i encourage you to look into.

    object creAtion bAsics

    eMbrAcing prototYpAl inheritAnce

  • 17/2

    7

    Before going any further, i want to clarify the term prototype. first, there is the prototype property of a constructor function as shown in the last sections example. there is another hidden property that is the actual prototype of an object. this can be very confusing. the ecmAScript proposal refers to this hid-den property as [[Prototype]]. this is exposed in some JavaScript environments as the __proto__ property, but this is not a standard part of the language and should not be counted on. when you cre-ate a new object using new with a constructor function, that new objects [[Prototype]] is set with a reference to the constructor functions prototype.

    in addition to this naming confusion, there were two design decisions made in the language that have added to the confusion ever since. first, due to the concern that some developers might not be comfort-able with prototypal inheritance, constructor functions and the new operator were introduced. Second, there was no direct native way to create a new object with another object as its [[Prototype]], except through the new operator with a constructor function.

    fortunately, most browsers now support the Object.create method. this method takes an existing ob-ject as a parameter. it returns a new object that has the existing object assigned as its [[Prototype]]. even more fortunately, this method is quite easy to create for those environments that do not support it:

    if(typeof Object.create !== function) { Object.create = function (o) { function F() {} F.prototype = o; return new F(); };}

    So, how would you rewrite the earlier example using Object.create? first you create a foo object that has a name property and a sayHello function:

    var foo = { name: foo, sayHello: function() { alert(hello from + this.name); }};foo.sayHello();

    then, you use Object.create to make a bar object that has foo as its prototype, and add a sayGood-bye function to it:

    var bar = Object.create(foo);bar.sayGoodbye = function() { alert(goodbye from + this.name);}bar.sayHello();bar.sayGoodbye();

    its also very common to create an extend function that simplifies the adding of methods and properties to the new object. the following method simply copies over any properties from props onto obj:

    function extend(obj, props) { for(prop in props) { if(props.hasOwnProperty(prop)) { obj[prop] = props[prop]; }}}

  • 18/2

    7

    this enables you to create bar like so:

    var bar = Object.create(foo);extend(bar, { sayGoodbye: function() { alert(goodbye from + this.name); }});

    not such a big deal here, but it simplifies things greatly when you are adding several more properties or methods.

    ok, now that you have the basics down, you can start putting them together in a real world scenario.

    the particles used in the example project are going to be very basic: black dots that move around in a two-dimensional space and bounce off the walls. they also support gravity and friction as needed. youll define a particle object that has all the properties and methods it needs, and place it in an adc object to avoid polluting the global namespace.

    here is the running example:

    creAting pArticles using object.creAte

  • 19/2

    7

    var adc = adc || {};

    adc.particle = { x: 0, y: 0, vx: 0, vy: 0, gravity: 0.0, bounce: -0.9, friction: 1.0, bounds: null, color: #000000, context: null,

    update: function() { this.vy += this.gravity; this.x += this.vx; this.y += this.vy; this.vx *= this.friction; this.vy *= this.friction;

    if(this.x < this.bounds.x1) { this.x = this.bounds.x1; this.vx *= this.bounce; } else if(this.x > this.bounds.x2) { this.x = this.bounds.x2; this.vx *= this.bounce; } if(this.y < this.bounds.y1) { this.y = this.bounds.y1; this.vy *= this.bounce; } else if(this.y > this.bounds.y2) { this.y = this.bounds.y2; this.vy *= this.bounce; } },

    render: function() { if(this.context === null) { throw new Error(context needs to be set on particle); } this.context.fillStyle = this.color; this.context.fillRect(this.x - 1.5, this.y - 1.5, 3, 3); }};

    next, youll need a particle system to keep track of all the particles and handle updating and rendering them.

  • 20/2

    7

    var adc = adc || {};

    adc.particleSystem = { particles: [],

    addParticle: function(particle) { this.particles.push(particle); },

    update: function() { var i, numParticles = this.particles.length;

    for(i = 0; i < numParticles; i += 1) { this.particles[i].update(); } },

    render: function() { var i, numParticles = this.particles.length; for(i = 0; i < numParticles; i += 1) { this.particles[i].render(); } }};

    And finally, youll need a main file that creates the system, creates and adds all the particles, and sets up the animation loop.

    (function() { if (typeof Object.create !== function) { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; }

    var system, numParticles, canvas, context, bounds;

    function initSystem() { system = Object.create(adc.particleSystem); numParticles = 200; canvas = document.getElementById(canvas); context = canvas.getContext(2d); canvas.width = window.innerWidth; canvas.height = window.innerHeight; bounds = { x1: 0, y1: 0,

  • 21/2

    7

    x2: canvas.width, y2: canvas.height }; }

    function initParticles() { var i, particle; for(i = 0; i < numParticles; i += 1) { particle = Object.create(adc.particle); particle.bounds = bounds; particle.context = context; particle.x = Math.random() * bounds.x2; particle.y = Math.random() * bounds.y2; particle.vx = Math.random() * 10 - 5; particle.vy = Math.random() * 10 - 5; system.addParticle(particle); } }

    function animate() { context.clearRect(bounds.x1, bounds.y1, bounds.x2, bounds.y2); system.update(); system.render(); } initSystem(); initParticles(); setInterval(animate, 1000 / 60);}());

    the code in this file is contained in an immediately invoked function expression, again to avoid global namespace pollution. it includes the Object.create shim for browsers that might need it. this is all pulled together in the following html file:

    Particles v1 .html, body { margin: 0; padding: 0; }

  • 22/2

    7

    the important lines, for the purposes of this article, are those that create the particle system:

    system = Object.create(adc.particleSystem);

    and that create the particles themselves:

    particle = Object.create(adc.particle);particle.bounds = bounds;particle.context = context;particle.x = Math.random() * bounds.x2;particle.y = Math.random() * bounds.y2;particle.vx = Math.random() * 10 - 5;particle.vy = Math.random() * 10 - 5;

    you havent implemented any kind of extend function yet, but you can see here where it would be use-ful calling extend a single time, rather than line after line of assigning properties. in the next iteration, youll add that and then some.

    for the second version of the particle system, rather than having the main file create and extend each and every particle by itself, it would be better to have the particles know how to create, extend, and ini-tialize themselves. to support that, you can use two new functions, extend and init , which are added to adc.particle :

    var adc = adc || {};

    adc.particle = { x: 0, y: 0, vx: 0, vy: 0, gravity: 0.0, bounce: -0.9, friction: 1.0, bounds: null, color: #000000, context: null,

    extend: function(props) { var prop, obj; obj = Object.create(this); for(prop in props) { if(props.hasOwnProperty(prop)) { obj[prop] = props[prop]; } } return obj; },

    init: function() { this.x = Math.random() * this.bounds.x2; this.y = Math.random() * this.bounds.y2; this.vx = Math.random() * 10 - 5;

    Adding eXtend And init

  • 23/2

    7

    this.vy = Math.random() * 10 - 5; }, // // rest of methods are the same as version 1};

    the extend method takes care of creating a new object, passing this as a parameter to Object.cre-ate. thus, it makes a copy of itself. it then takes any properties that were passed into extend, copies them onto the new object it created, and finally returns the new object.

    now, rather than calling Object.create(adc.particle) and setting and tweaking property after property, you can call adc.particle.extend, passing in an object with the properties you want to set, and then call init on the newly created particle.

    when you add the extend method to the particle system, the main file becomes a bit simpler. in init-System, you call adc.particleSystem.extend() to create the new system. you dont need to add any properties to the system, so extend is called with no parameters. not much of a change there:

    function initSystem() { system = adc.particleSystem.extend(); numParticles = 200; canvas = document.getElementById(canvas); context = canvas.getContext(2d); canvas.width = window.innerWidth; canvas.height = window.innerHeight; bounds = { x1: 0, y1: 0, x2: canvas.width, y2: canvas.height }; }

    in the initParticles method, though, you see an improvement:

    function initParticles() { var i, particle; for(i = 0; i < numParticles; i += 1) { particle = adc.particle.extend({ bounds: bounds, context: context }); particle.init(); system.addParticle(particle); } }

    now you can call adc.particle.extend to create each particle, passing in an object that contains the bounds and context, which are then copied to each particle. finally, you just call init on the new particle, which takes care of randomly setting up its position and velocity. this version works exactly the same as the last, but the creation of individual particles has been greatly simplified.

  • 24/2

    7

    the third version of the particle system supports inheritance. this is key to code reuse. you have one type of object and you want to make another type of object that is slightly different. you dont want to com-pletely recreate the first object with just a couple of changes.

    code reuse has two important benefits. first, there is less code to write. you certainly dont want to write the same code twice. you also dont want to copy and paste code, as this can lead to things getting out of sync, with a function implemented one way over here and the same function implemented a bit differ-ently over there. the second benefit is better performance. when you have the same code duplicated in your live application, it takes longer to download, eats up more memory, and can cause your code to be slower, particularly in object instantiation (because it is instantiating the same code again and again).

    the particle system currently renders to an html5 canvas. now, you may want to make a different parti-cle type that renders itself as a Dom object. ideally, almost all of the particle code would be reused, with only the render method differing. So, with great confidence, you can just take particle.js and remove the render method from it.

    next, make two new files, canvasparticle.js and comparticle.js. the canvas version will be similar to what youve just done:

    var adc = adc || {};

    adc.canvasParticle = adc.particle.extend({ render: function() { if(this.context === null) { throw new Error(context needs to be set on particle); } this.context.fillStyle = this.color; this.context.fillRect(this.x - 1.5, this.y - 1.5, 3, 3); }});

    this code is quite simple. you just call adc.particle.extend, passing in an object that contains your old render method. this will create a new object that has particle as its [[Prototype]], and ren-der as a new method directly on the object.

    next youll have to change main.js a bit to allow for your new object types. create a maincanvas.js file for setting up the canvas-based particles. it will only differ in one line, where it uses the adc.canvas-Particle type to instantiate particles, rather than just adc.particle:

    function initParticles() { var i, particle; for(i = 0; i < numParticles; i += 1) { particle = adc.canvasParticle.extend({ bounds: bounds, context: context }); particle.init(); system.addParticle(particle); }}

    Adding inheritAnce

  • 25/2

    7

    the particleSystem.js file can remain unchanged, but of course the html file will have to reflect new source files youve created. this example should function identically to the first two versions.

    now youre ready to create the Dom version.

    the domparticle.js file will be almost as simple as canvasparticle.js. it assumes that there is an element it can position, and positions it using style properties:

    adc.domParticle = adc.particle.extend({ render: function() { if(this.element === null) { throw new Error(element needs to be set on particle); } this.element.style.left = this.x; this.element.style.top = this.y; }});

    But in this example, the html file and main.js file will need to change significantly. in addition to refer-encing different source files, the html file can eliminate the canvas element and add a container div in which to put all the particle elements:

    Particles v3 .html, body { margin: 0; padding: 0; overflow: hidden; }

    the main.js file will become mainDom.js and will obviously need to change a bit to create domParticles and give them individual elements instead of references to the canvass context.

  • 26/2

    7

    (function() {

    var system, numParticles, container, bounds;

    function createElement() { var el = document.createElement(div); el.style.position = absolute; el.style.width = 3; el.style.height = 3; el.style.backgroundColor = #000000; container.appendChild(el); return el; } function initSystem() { system = adc.particleSystem.extend(); numParticles = 200; container = document.getElementById(container); bounds = { x1: 0, y1: 0, x2: window.innerWidth, y2: window.innerHeight }; }

    function initParticles() { var i, particle; for(i = 0; i < numParticles; i += 1) {

    particle = adc.domParticle.extend({ bounds: bounds, element: createElement() }); particle.init(); system.addParticle(particle); } }

    function animate() { system.update(); system.render(); }

    initSystem(); initParticles(); setInterval(animate, 1000 / 60);

    }());

  • About this Article

    keith peters is a JavaScript and flash / Ac-tionScript developer in the Boston area. he writes books, speak at conferences, blogs and is an avid jogging & fitness expert. keith is well-known for several books including foundation html5 Animation with Java-Scripthttp://www.bit-101.com

    @bit101

    Prototypal Inheritance in javaScripthttp://javascript.crockford.com/prototypal.html

    Classical Inheritance in javaScripthttp://javascript.crockford.com/inheritance.html

    javaScript Objectshttp://javascriptjabber.com/005-jsj-javascript-objects/

    online resources

    this makes use of a new function, createElement, that simply creates a div, styles it, and adds it to the container div. this is what the particle will position when its render method is called.

    this final example should be nearly identical to all the other versions. of course, there are lots of optimi-zation and enhancements that you can do to improve all of these examples. i purposely kept it simple to better illustrate the inheritance aspect.

    you may still prefer constructor functions and the new operator. im not going to twist your arm about it. i personally find this method of object creation to be very clean and in accord with the basic prototypal nature of JavaScript.

    i encourage you to explore the source code provided in the sample files for this tutorial and try out the particle system in a browser that supports html5.

    As your needs for more complex apps grow, you can add features onto this basic setup far more cleanly than you can with an pseudo-class based system. for more information, see the following resources:

    - Douglas crockfords prototypal inheritance in JavaScript

    - Douglas crockfords classical inheritance in JavaScript

    - wooDy2ShoeSs 005 JSJ Javascript objects

    where to go froM here

  • appliness( DONT WORRY, BE APPLI

    CRAFTING NATIVE LOOKING IOS APPS WITH HTML, BACKBONE.JS AND PHONEGAPive Been Blogging A lot ABout BAckBone.JS Recently. BAckBone.JS iS A lightweight ARchitectuRAl fRAmewoRk thAt BRingS StRuctuRe to youR weB ApplicAtionS. BAck-Bone iS not, howeveR, A uSeR inteRfAce fRAmewoRk thAt helpS you with the wAy youR ApplicAtion lookS.

    by christophe coenraets

    bAcKground

    for traditional web apps (delivered through a browser), twitter Bootstrap can help (read here). But what about mobile apps? i explored Backbone.js + jquery mobile here. Depending on what you are looking for, it may or may not be the right solution: jqm provides mobile skins, but they dont look native. its also more of a full stack framework than a lightweight ui toolkit that you can easily layer on top of your app.

    the alternative to using an existing ui toolkit is to roll your own styles to make your application look and behave like a native app. Sounds easy enough, but when you consider all the details and want to achieve pixel perfection, it becomes a daunting task.

    Playground

    - Bootstrap

    - jQuery Mobile

    - PhoneGap

    Difficulty- rookie- intermediate

    - expert

    Todo list- look native- perform- fire Jim

    28/2

    9

    So, where do you turn to for help when you need to make your application look good?

  • As i was getting ready to tackle the challenge, and build a new native looking version of my employee Di-rectory app, i came across this great blog post by chee Aun where he documents the process he went through to build his own hacker news mobile app. his post is a real gem, and i ended up reusing a lot of the hacker news app styles. compared to the hacker news app, the employee Di-rectory page flow is more random. here are a few ex-amples:1. *-Searchpage -> employeepage -> Reportspage -> em-

    ployeepage -> 2. Searchpage -> employeepage -> employeepage (man-

    ager) -> Reports -> 3. Searchpage -> employeepage -> employeepage (man-

    ager) -> employeepage (managers manager) ->

    As you can see, the page flow includes same page transitions, when the user navigates from one employ-ee to his/her manager. to accommodate the employee Directory page flow requirements, my Backbone.js in-frastructure creates and destroys pages as needed with the appropriate slide-in/slide-out transitions. the im-plementation of these transitions was inspired by wes-ley hales article.

    source code

    i updated the backbone-directory github repository to include this version: it is available in the iphone directory.

    phonegap

    even though you can run this application in a browser (here), i built it with the intention of packaging it as a native app with phonegap so that you could start it like any other app from your iphone home screen. if you are not familiar with phonegap, ill provide more de-tails on packaging this app as a native app in my next post.

    About this Article

    christophe coenraets is a technical evange-list for Adobe where he focuses on mobile and Rich internet Applications for the en-terprise. in his previous role at macromedia, christophe worked on JRun, the companys J2ee application server.http://coenraets.org/

    @ccoenraets

    jQuery Mobile official websitehttp://jquerymobile.com/

    Backbone.js official websitehttp://documentcloud.github.com/backbone/

    Backbone-jQuery mobilehttps://github.com/ccoenraets/backbone-jquerymobile

    online resources

  • appliness( DONT WORRY, BE APPLI

    USING BACKBONE.JS WITH JQUERY MOBILEBAkcBone.JS iS An ARchitectuRAl fRAmewoRk thAt helpS you wRite well-StRuctuReD weB ApplicAtionS. it iS not, howeveR, A uSeR inteRfAce fRAmewoRk AnD it theRefoRe DoeSnt help you with the wAy youR ApplicAtion lookS.

    by christophe coenraets

    Quest for A Mobile ui toolKit

    After that post, i wanted to create a mobile version of the same application; a version that i could package with phonegap and that would look and behave like a native app. twitter Bootstrap can probably be tweaked for that purpose as well, but i was looking for a ui toolkit dedicated to providing native looking controls and behaviors on mobile devices.

    Playground

    - Backbone

    - jQMobile

    - HTML DOM

    Difficulty- rookie- intermediate

    - expert

    Todo list- catch event- use bootstrap- structure code

    30/3

    3

    Backbones confined scope is a good thing: its lightweight, non-intrusive, not coupled to things you dont need, and it lets you use the ui toolkit of your choice or simply roll your own styles and widgets. in my previous post, i demonstrated how to use twitter Bootstrap on top of Backbone.

  • sAMple ApplicAtion

    jquery mobile (jqm) is one option that ive explored before (here and here), but it fits more in the cat-egory of full-stack frameworks that tie together architectural structure and ui controls and behaviors. John Bender, my colleague at Adobe and member of the jquery mobile team, recently pointed out to me that you can disable the routing and navigation capabilities of jqm, and essentially use it as a pure ui framework on top of other architectural frameworks like Backbone.js.

    31/3

    3

    Another wAY to use jQuerY Mobile

    i ended up spending a decent amount of time trying different things to get the two frameworks to play well together without stepping on each other. to save you some headaches if you are trying to do the same, i put together a simple application with the basic setup to combine Backbone (for the applica-tion structure and routing) and jquery mobile (for its styles and widgets).

    note: Another approach would be to use jqms routing instead of Backbones. Ben nolan has an example of this approach here. i prefer to use Backbones routing because i find it more flexible and less page-centric.

    here is the app:

    click here to run the application in a separate window. the source code is available in this github re-pository.

  • $(document).bind(mobileinit, function () { $.mobile.ajaxEnabled = false; $.mobile.linkBindingEnabled = false; $.mobile.hashListeningEnabled = false; $.mobile.pushStateEnabled = false;});

    $($(div[data-role=page]).live(pagehide, function (event, ui) { $(event.currentTarget).remove();});

    $.mobile.hashListeningEnabled = false; $.mobile.pushStateEnabled = false;

    32/3

    3

    how it worKs

    the key to this approach is to disable jquery mobiles routing: in other words, you need to tell jque-ry mobile not to handle links, hash tag changes, and so on. i isolated that code in jqm-config.js:

    if jquery mobile is not in charge of page navigation, you also have to manually remove the pages from the Dom when they are not used anymore. here is one way to do it:

    with this configuration in place, you use Backbones routing as usual:

    var AppRouter = Backbone.Router.extend({ routes:{ :home, page1:page1, page2:page2 }, home:function () { this.changePage(new HomeView()); }, page1:function () { this.changePage(new Page1View()); }, page2:function () { this.changePage(new Page2View()); }, changePage:function (page) { $(page.el).attr(data-role, page); page.render(); $(body).append($(page.el)); $.mobile.changePage($(page.el), {changeHash:false}); } });

  • source code

    the source code is available in this repository on github.

    is this the right stAcK?

    i like the idea of a lightweight architectural framework combined with a ui toolkit. Backbone + twitter Bootstrap felt right because the two frameworks have different areas of concern and complement each other very well. i was happy to see you could decouple jqm from its navigation infrastructure. however, thats probably not the main design center at this point. i think it would be interesting for jqm to fo-cus on that utilization scenario as well. At the end of the day, frameworks are often a matter of personal preferences, and not all applications are equal. So try it, see if it works for you, and share your experi-ence. what ui toolkit are you using?

    A More reAl-life ApplicAtion

    in my next post, ill share a Backbone.js + jquery mobile version of the employee Directory applica-tion first explored with Backbone.js + twitter Bootstrap.

    backbone & twitter

    jQuery & phonegap

    jQuery getting started

    john bender

    bennolan

    sampleApp

    About this Article

    christophe coenraets is a technical evange-list for Adobe where he focuses on mobile and Rich internet Applications for the en-terprise. in his previous role at macromedia, christophe worked on JRun, the companys J2ee application server.http://coenraets.org/

    @ccoenraets

    jQuery Mobile official websitehttp://jquerymobile.com/

    Backbone.js official websitehttp://documentcloud.github.com/backbone/

    Backbone-jQuery mobilehttps://github.com/ccoenraets/backbone-jquerymobile

    online resources

    MORE INFORMATION> >

  • appliness( DONT WORRY, BE APPLI

    DEMO OF HANDLEBARS, AND WHY YOU SHOULD CONSIDER A TEMPLATING ENGINEi hAD heARD ABout hAnDleBARS fRom vARiouS people. itS AlSo the templAting engine thAt emBeR.JS uSeS. hAnDleBARS woRkS By Allowing you to Define templAteS uSing Simple ScRipt BlockS

    by Raymond camden

    A jAvAscript teMplAting engine

    for a while now ive been thinking i need to pick up, and start using, a JavaScript templating engine. i had used a jquery-based one a few years back, but that project was abandoned and ive yet to really look what - if any - solution would work good for me. Another reason ive not found the time is that a majority of my JavaScript examples are small little demos built for blog posts. when i blog, i try my best to keep my code as simple as possible. i dont go all mvc just to demonstrate date formatting. it may not be real world, but it also keeps you focused on the topic im trying to discuss. today i made the time - and more specifically - made a demo. the demo is stupid. its not even important.

    what is important is this: if youve ever used JavaScript to build strings of html, you never realized just how much of a pain that is until you dont have to. you never realized how resistant you are to adding new features - or tweaking the design. you never realized how much you held back - just be-cause of how much of a pain in the rear it was!

    Playground

    - Handlebars

    - Templates

    - Ember

    Difficulty- rookie- intermediate

    - expert

    Todo list- shave- MVC- use gravatar

    34/4

    0

  • 35/4

    0

    im probably being overly dramatic, but to me, it feels a lot like oRm. yeah, its simple to go into a database client, open a table, and add a new field. But when you can do all of that via code... it feels incredibly freeing. you feel yourself trying new and interesting things. in fact, the demo im going to show has about twice the features i was planning just because it was so damn easy to add.thats how i feel today - and any day where my computer makes me smile is a good day. ok, enough rambling.

    i had heard about Handlebars from various people. its also the templating engine that ember.js uses. handlebars works by allowing you to define templates using simple script blocks, so for example, you can write your template in your document like so:

    {{title}} {{body}}

    you then use the handlerbars Api to create a template out of the block, apply data to it, and then ren-der it to screen. its all relatively simple, but the docs dont necessarily do a great job i think of demon-strating simple examples in full pages so you can see things in context. here is a trivial example:

    Test 1 Your Bio Your name is {{firstname}} {{lastname}} and you are {{age}} years old.

    Render Simple Bio

    Demo

    document.addEventListener(DOMContentLoaded, function() {

    //Get the contents from the script block var source = document.querySelector(#result-template).innerHTML;

  • 36/4

    0

    //Compile that baby into a template template = Handlebars.compile(source);

    document.querySelector(#demoButton).addEventListener(click, func-tion() { var fname = document.querySelector(#firstname).value; var lname = document.querySelector(#lastname).value; var age = document.querySelector(#age).value;

    var html = template({firstname:fname, lastname:lname,age:age}); document.querySelector(#resultDiv).innerHTML = html;

    }); });

    notice how ive got a simple template block on top. if youve never seen handlebars before, or any Ja-vaScript templating engine, you can probably guess which portions of the block represent dynamic por-tions and which represent static text.

    ive got a simple form with a button bound to a simple click listener. looking at the JavaScript, you can see that first i have to grab the html from the template block. i then compile this. this gives me a template that i can reuse to generate output.

    my form has a simple click handler. when you hit the button, i pass the values to my template and grab the html out of it. you can play with this demo here:

  • 37/4

    0

    dYnAMic teMplAtes

    of course, not every template will be a simple set of keys and values. your template may also need to be dynamic based on the values passed in. lets look at another example that makes use of both lists and conditionals.

    Test 2 Your Favorite Things

    {{#if things}} {{#each things}} {{this}} {{/each}} {{else}}

    Apparently, you like nothing. Poor you.

    {{/if}}

    List of Things Enter a comma-separated list of things you like. Demo

    document.addEventListener(DOMContentLoaded, function() {

    //Get the contents from the script block var source = document.querySelector(#result-template).innerHTML; //Compile that baby into a template template = Handlebars.compile(source);

    document.querySelector(#demoButton).addEventListener(click, func-tion() { var things = document.querySelector(#things).value;

  • 38/4

    0

    if(things.length) var arrThings = things.split(,);

    var html = template({things:arrThings}); document.querySelector(#resultDiv).innerHTML = html;

    }); });

    in our template, weve got two things going on here. first is a conditional that checks if things is a truthy value (truthy being one of the things that make JavaScript so fun). within the true part of the conditional we use an each block to enumerate over a set of values.

    if you scroll down to the html/JavaScript, you can see im just asking for you to enter a list of things you like. that value is split into an array and passed (if there were values) to the template.

    Demo is below:

  • 39/4

    0

    custoM functions

    lets look at one more example. one of the cooler aspects of handlebars is that you can add custom functions to the engine. for example, you could write a cowbell function that wraps your results in the beautiful rocking sounds of the cowbell. ok, maybe not that. But what about something a bit complex - like converting an email address into a mD5 hash that could be used for gravatar? yeah - no way that would work...

    Test 3 You and Your Gravatar Your email is {{email}} and your gravatar is:

    Enter Email Address for Awesomeness Demo

    document.addEventListener(DOMContentLoaded, function() {

    //Tip on using Gravar with JS: http://www.deluxeblogtips.com/2010/04/get-gravatar-using-only-javascript.html Handlebars.registerHelper(gravatarurl, function(email) { return http://www.gravatar.com/avatar/ + MD5(email) + .jpg?s=250; });

    //Get the contents from the script block var source = document.querySelector(#result-template).innerHTML; //Compile that baby into a template template = Handlebars.compile(source);

    document.querySelector(#demoButton).addEventListener(click, func-tion() { var email = document.querySelector(#email).value; if(!email.length) return;

    var html = template({email:email});

  • document.querySelector(#resultDiv).innerHTML = html;

    }); });

    notice in the template we have one simple value, email, and then this: gravatar email. this isnt some-thing built into handlebars, but rather, injected via the registerhelper function you see in the main script block of the page.

    the demo is below:

    About this Article

    meet Raymond camden. he is a 38 year old married father of three living in beautiful la-fayette, louisiana. Ray is a developer evan-gelist for Adobe where his primary technical focus is coldfusion, jquery, flex, AiR and the mobile space.

    http://raymondcamden.com/ @cfjedimaster

    Full tutorial with codehttp://www.raymondcamden.com/index.cfm/2012/4/19/Demo-of-Handlebars-and-why-you-should-consider-a-templating-engine

    Handlebarshttp://handlebarsjs.com/

    Emberhttp://emberjs.com/

    online resources

  • appliness( DONT WORRY, BE APPLI

    REAL-TIME DATA ExCHANGE IN HTML5 WITH WEBSOCKETSthe weBSocket Api iS one of the moRe poweRful new feAtuReS in the html5 Specifi-cAtion BecAuSe it openS the DooR to ReAl-time communicAtion AnD puShing meS-SAgeS. thiS ARticle DeScRiBeS A BASic chAt pRogRAm thAt ShowS the BASicS of weB-SocketS AnD how to implement them on the client SiDe.

    by Ryan Stewart

    using websocKets

    the webSocket Api has been somewhat volatile over the past year as the w3c specification has been solidified. it has finally been completed and the specification can now be implemented consistently across browsers.

    Why use WebSockets?instead of using the http protocol, webSockets use their own protocol. there is a significant amount of overhead incurred whenever communication over http happens. Because of the request/response mechanism and all of the information that http stores in header information, exchanging even basic information can result in lots of data being sent back and forth.

    webSockets, by contrast, are full duplex, which means they can communicate back and forth at the same time without the request/response overhead. the header information is also much smaller, so the bulk of the data being exchanged is the actual data from the application.

    Playground

    - real-time

    - messages

    - sockets

    Difficulty- rookie- intermediate

    - expert

    Todo list- hike- build a chat- read the spec

    41/4

    7

  • Browser Support for WebSocketsmost of the major browsers now support some version of webSockets. firefox, chrome, and the latest version of internet explorer all have added support for the webSocket Api. Safari and opera offer par-tial support for the Api.

    one of the major issues is understanding which draft of the webSocket spec is supported by the browsers. wikipedia has a good entry that lists the specifications by version number and which browser versions support them; for details, visit http://en.wikipedia.org/wiki/webSocket#Browser_support. go-ing forward, the final version of the specification, Rfc 6455, is the one that will be implemented.

    Setting Up a Serverwhen working with webSockets, you need to have a server that supports them. complete instructions for configuring a server that adheres to the webSockets specification are beyond the scope of this ar-ticle, but its an important enough topic to address at least briefly. there are a few different ways to po-tentially implement webSockets.

    php ships with built-in support for webSockets, so you could write your own php socket server that handles the requests and responses from the client code. there are also Java and Ruby projects that provide webSocket support for those languages.

    one of the more interesting ways to get up and running is a project called Socket.io that runs on node.js. it has server-side and client-side libraries that make using webSockets very easy. node.js lets you use JavaScript on the server so the client- and server-side languages can be the same. for basic socket testing, websocket.org hosts a test server at http://websocket.org/echo.html that will simply send the transmitted data as a response back to the client.

    the server i use comes from kevin hoyt who wrote a socket server using Adobe AiR. for details, see the AiRwebSocket project on github.

    connecting to a websocket server

    the core of the webSocket Api is the webSocket class, which provides the methods and events that handle all of the communication with the server.

    it is important to have your code first check that the browser supports webSockets. the quickest way to do this is to see if window.WebSocket exists. A more powerful solution is to use the modernizr li-brary, which helps detect support for webSockets while providing a graceful fallback for older brows-ers.

    the example chat application provides a connect button that the user can use to initiate the connec-tion to the socket server. this process is implemented in a connect() function:

    var connection = {};function connect() {if(window.WebSocket != undefined) {

    if(connection.readyState === undefined || connection.readyState > 1) { connection = new WebSocket(ws://localhost:1740); }}}

    42/4

    7

  • 43/4

    7

    the first line of code above defines the connection object that will be used by the rest of the applica-tion. when you make it a global variable, the connection object can be used in other functions. After checking to make sure that the browser supports webSockets, the code checks to make sure there isnt already a connection active.

    the webSocket object provides a readyState property that indicates the connections ready status. the values are as follows:

    const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSING = 2; const unsigned short CLOSED = 3;

    As long as the readyState is greater than 1, the connection isnt open so the application can connect to the socket server.

    connecting to the server is just a matter of instantiating the webSocket class and passing in the uRl and port number of the socket server. the browser then makes a connection with the server.

    Handling the WebSocket object in Firefoxthe webkit browsers and opera handle webSockets in the same way, but in firefox the webSocket object has a prefix; it is referred to as MozWebSocket. Beyond that, the Apis are the same, so an easy way to keep everything simple is to check for the existence of window.MozWebSocket and then set it to the regular webSocket object.

    if (window.MozWebSocket) { window.WebSocket = window.MozWebSocket;}

    The open eventif the connection is successful, the browser will fire an open event. to make sure this gets caught, the webSocket Api includes an onopen property, which is assigned to a function that will run code for ev-ery open event.

    the code below sets the onopen property to a corresponding onopen() function that sets a couple of variables so that the ui is updated to indicate that the user is logged in.

    window.WebSocket

    here is the onopen() function:

    function onopen (event) {document.getElementById(connected).innerHTML = Connected;document.getElementById(chat).innerHTML = You have joined the chat;}

    note that most people dont actually assign those methods to named functions but rather include them in anonymous functions right where they are first defined. i have implemented it this way because i like having the separation, but it may seem a bit redundant to you as you dig into more webSocket exam-ples.

  • 44/4

    7

    Managing data

    now that your client is connected you can start dealing with actual chat messages. the server i have set up for the moment just cycles through all of the currently connected users whenever it gets a mes-sage and then sends that message out to all of those users. though it is a pretty basic chat server, it il-lustrates many key webSocket concepts.

    Sending messageswith webSockets you can send text, or utf-8 data, as well as binary data such as pictures or videos. they both use the same Api on the client side, but it will largely depend on the server to actually han-dle the data types correctly.

    to send a message to the socket server the chat application simply invokes the send() method of the connection object. it takes a single parameter, the message being sent, which it passes to the socket server.

    when the user clicks on the Send message button in the chat application, the sendmessage() meth-od sends the message typed by the user along with the username. the socket server will then loop through all the clients, including the sender, and deliver the message to them.

    function sendmessage() {var messagetext = document.getElementById(chatmessage).value;messagetext = username + : + messagetext;connection.send(messagetext);}

    Receiving messagesto handle incoming messages, the webSocket Api uses the onmessage property of the connection event. Just like the onopen property covered earlier, this property takes a function that will be called whenever a new message arrives. So the first step is to set up the event handler in the original connect() method right before the onopen definition:

    connection.onmessage = onmessage;

    once that is set up, define the onmessage() function:

    function onmessage (event) {var chatdiv = document.getElementById(chat);chatdiv.innerHTML = chatdiv.innerHTML + event.data + ;}

    the event that is received by onmessage is of type MessageEvent . it includes a data property that has the value of the message being received. in this case, that is used to display the chat text. this data property includes the username of the chat participant along with the message they sent. this value is appended to the chat div window.

  • 45/4

    7

    Handling errorserror handling is an important topic to cover, even if only quickly. Along with onopen and onmessage, the webSocket Api also includes an onerror property, which takes a function that runs any time an error occurs. the error event includes a data property that provides some information about the error.

    here is the basic error handler used in the chat application:

    function onerror(event) {console.log(event);document.getElementById(chat).innerHTML = There was an error: + event.data;}

    going binary

    By enabling the exchange of real-time data, the webSocket Api opens some interesting possibilities when combined with the rest of the host of new html5, JavaScript, and cSS3 features.

    one of the cooler demos ive seen is a collaborative whiteboard using the canvas element. every time someone connected to the socket draws on it, a message gets sent out to the connected clients so ev-eryone can see what is being drawn. its a neat idea, but all thats really happening under the hood is that the socket server and application are exchanging a set of x and y coordinates in text.

    to illustrate the binary capabilities of the webSocket Api, i implemented a similar application that uses binary data. Specifically, i implemented a quick canvas painting feature that the user can use to draw something on a small canvas area. when the user clicks a button, the application does not send a set of coordinates to the socket server, but rather takes a snapshot of the image and sends it as binary data to the socket server. the socket server sends the data back as an image, which will appear in the chat window of all connected clients. this demo will only work in the latest version of chrome because bina-ry webSocket support is still somewhat on the cutting edge.

    Creating binary datato send and receive binary data correctly you need to set up a binaryType for the webSocket Api. the binaryType can be either arraybuffer or blob , which are the two basic binary types that Ja-vaScript supports. you can use either one depending on what youre sending and how you want to ac-cess it. i found arraybuffer to be ideal for this example because its easy to iterate through an array, and i found that i had to copy a lot of data back and forth between arrays. So the webSocket setup code becomes this:

    connection = new WebSocket(ws://localhost:1740);connection.binaryType = arraybuffer;connection.onopen = onopen;connection.onmessage = onmessage;connection.onclose = onclose;connection.onerror = onerror;

  • 46/4

    7

    now you need to get binary data out of the canvas. i wrote a sendphoto() method that does the work of pulling the binary data out of the canvas element on the page. it uses the getImageData() method to get the actual binary array data and then it loops through the data and inserts it into a Uin-t8Array. the code accesses the buffer property of this array and sends it using the webSocket Api.

    function sendphoto() {

    imagedata = context.getImageData(0, 0, imagewidth,imageheight);

    var canvaspixelarray = imagedata.data;

    var canvaspixellen = canvaspixelarray.length; var bytearray = new Uint8Array(canvaspixellen);

    for (var i=0;i

  • var imgdata = tempcontext.getImageData(0,0,imagewidth,imageheight);

    var imgdatalen = imgdata.data.length;

    for(var i=8;i >

  • appliness( DONT WORRY, BE APPLI

    SWIPE TO DELETE ITEMS WITH JQUERY MOBILE ON TOUCH DEVICESthe Swipe geStuRe hAS Been BRoADly uSeD on liSt to Remove itemS, eSpeciAlly in nA-tive ioS ApplicAtionS. letS coDe thiS BehAvioR with JqueRy moBile.

    by michal chaize

    getting closer to nAtive behAvior

    hybrid applications raise a lot of ui and technical challenges. using web standards, developers are work-ing hard to reproduce native ui behaviors without impacting the global performance of their applica-tion. the swipe gesture is one of them. today, jquery mobile handle swipe events which are triggered when a horizontal drag of 30px or more occurs within 1 second duration. But these thresholds can be configured.

    to play with this event, well use a simple jquery mobile list and manage a two-step deletion task. first, the user will swipe on an item. then, an active delete button appears to confirm the deletion. the swipe gesture is ideal for actions that requires an user confirmation.

    Playground

    - jQuery mobile

    - ToggleClass

    - Events

    Difficulty- rookie- intermediate

    - expert

    Todo list- swipe left- buy milk- try on iOS

    48/5

    2

  • 49/5

    2

    LOADING THE APPLICATION

    here is the running sample of this tutorial. its a simple html page that creates a list of items from an xml file. if you swipe your finger on an item, a delete button appears. if you press the delete button, the row will fade out and be removed from the list. try it!

    how does it work? the delete buttons are hidden with a height of 0px. well use the toggleclass method to mod-ify the style of a delete button when a swipe item is triggered. the project contains two files, an html page and a JavaScript file. click on this icon to get more details about a section of the code:

    Ready for some code? go to the next page of this tutorial.

    try mei

    plAY with the finAl ApplicAtion

  • 50/5

    2

    swipe div.menu{ height: 0px; overflow:hidden; position:absolute; top:0; right:0; -webkit-transition: all 0.2s ease-in-out; } div.menu.active { position:absolute; top:0; right:0; width:160px; height:50px; } .myItem{ height:40px; vertical-align:middle; } .ui-btn{ width:140px; } .myItem.active{ color:#CC0000; } Swipe events

    i

    i

    i

    i

    i

    the htMl pAge

  • 51/5

    2

    $( document ).delegate(#page1, pageinit, function() { $.ajax({ type: GET, url: questions.xml, dataType: xml, success: function(xml){ var i=0; var myItems = ; $(xml).find(question).each(function() { var titleQuestion = $(this).find(title).text(); myItems += +titleQuestion+Delete; i = i+ 1; }); $(#listQuestions).html(myItems); $(#listQuestions).listview(refresh); $(#listQuestions).trigger(create); addBinding(); } }); }); function addBinding(){ for(var j=0; j< $(#listQuestions li).size();j++){ $(#listItem+j).bind(swipe,function(event) { $(div.menu, this).toggleClass(active); $(div.myItem, this).toggleClass(active); }); $(#myButton+j).attr(index,j); $(#myButton+j).bind(tap,function(event) { theIndex = $(# + event.currentTarget.id).attr(index); $(#listItem+theIndex).fadeOut(500,function(){ $(#listItem+theIndex).remove(); }) ; }); } }

    i

    i

    i

    ii

    i

    the jAvAscript code

  • About this Article

    michal chaize is a Developer evangelist at Adobe where he focuses on Rich internet Application and mobile applications. Based in paris, he works with large accounts that need to understand the benefits of rich user interfaces. hes the editor in chief of Appli-ness.http://riagora.com/

    @mchaize

    jQuery Mobile official websitehttp://jquerymobile.com/

    PhoneGap official websitehttp://www.phonegap.com

    Using jQuery mobile themeshttp://www.adobe.com/fr/devnet/dreamweaver/articles/theme-control-jquery-mobile.html

    online resources

    i hope that you enjoyed the tips inside the source of this tutorial. the main ones used to achieve this sample were:

    - ToggleClass()this is a very useful jquery method to manipulate class attributes. the easiest way to define transi-tions between states in your html apps is to declare two cSS styles, declare a transition in the default one and use toggleclass() on your elements.

    - .trigger(create)when you add elements dynamically within your code, you may want to force jquery to start again the analysis of your Dom elements.

    - .attr(index,j)its an easy to flag your dynamically added html elements. attr() sets attributes to a set of elements.

    - Use pageInit(), not $document.ready()the first thing you learn in jquery is to call code inside the $(document).ready() function so everything will execute as soon as the Dom is loaded. however, in jquery mobile, Ajax is used to load the con-tents of each page into the Dom as you navigate, and the Dom ready handler only executes for the first page. to execute code whenever a new page is loaded and created, you can bind to the pageinit event.

    - Swipe event (from the jQuery mobile documentation)triggers when a horizontal drag of 30px or more (and less than 20px vertically) occurs within 1 second duration but these can be configured:

    - scrollSupressionthreshold (default: 10px) More than this horizontal displacement, and we will suppress scrolling- durationthreshold (default: 1000ms) More time than this, and it isnt a swipe- horizontalDistancethreshold (default: 30px) Swipe horizontal displacement must be more than this.- verticalDistancethreshold (default: 75px) Swipe vertical displacement must be less than this.

    - More swipe eventsyou can also use the swipeleft and swiperight events.

    the swipe gesture is a classic on ioS, but the ui pattern is completely different on Android for instance. for each mobile platform, you need to learn the best ui best practices and discover how to code them using web standards. thats a big challenge, but a funny one.

    tips froM this tutoriAl

  • DOWNLOAD THE SOURCE CODE

    OF ALL THE TUTORIALS ON YOUR DESKTOP:

    http://appliness.com/code/02.zip

    appliness( GET THE SOURCE CODE

  • appliness( LIBRARY OF THE MONTH

    APP-UI BY ANDREW TRICEApp-ui iS A collection of ReuSABle ApplicAtion contAineR uSeR inteRfAce componentS thAt mAy Be helpful to weB AnD moBile DevelopeRS foR cReAting inteRActive ApplicAtionS uSing html AnD JAvAScRipt, eSpeciAlly thoSe tARgeting moBile DeviceS.

    app-ui is a continual work in progress it was born out of the necessity to have rich & native-feeling interfaces in html/JS experiences, and it works great with phonegap applications (http://www.phonegap.com).

    app-ui can easily be styled/customized using cSS.

    All of app-ui was created using html, cSS, & JavaScript. All animations are rendered using cSS3 translate3d, so that they are hardware accelerated (where supported). app-ui works well on ioS, An-droid and BlackBerry browsers (others not tested), and works well on the latest releases of most desk-top browsers (i know it does not work on old versions of ie).

    54/5

    8

  • you might be wondering why create this? when there are other open source alternatives like jquery mobile. the primary motivation for creating app-ui was to have reusable application containers that are highly performant, and do not force any prescriptive development paradigms. with respect to ani-mations/transitions, app-ui outperforms the alternatives, particularly on mobile devices.

    app-ui can be used with many different existing frameworks app-ui only requires jquery as a solu-tion accelerator framework. it will work with existing ui widget frameworkss (jQuery UI, Twitter Boot-strap, etc), and will work with existing templating frameworks (Moustache, Knockout, Handlebars, etc).

    app-ui currently has three application containers, and at this time it is not intended to be a complete ui widget framework.

    ViewNavigatorthe viewnavigator component allows you to create mobile experiences with an easily recognizable mobile ui paradigm. you use this to push & pop views from the stack.

    whY A new nAvigAtor?

    ApplicAtion contAiners

    55/5

    8

  • 56/5

    8

    the viewnavigator component allows you to create mobile experiences with an easily recognizable mo-bile ui paradigm. you use this to push & pop views from the stack. Some code used in the sample:

    $(document).ready( function() { //Setup the default view var defaultView = getView(); defaultView.backLabel = null; //Setup the ViewNavigator window.viewNavigator = new ViewNavigator( body ); window.viewNavigator.pushView( defaultView );} ); function pushView() { //create a view and push it onto the view navigator var view = getView(); window.viewNavigator.pushView( view );} function popView() { //pop a view from the view navigator window.viewNavigator.popView();} function getView() {//create a view descriptor with random content var bodyView = $( + Math.random().toString() + push view pop view + get-Meat() + ); var links = bodyView.find(a); return { title: Default View + parseInt(Math.random()*1000), backLabel: Back, view: bodyView };}

  • 57/5

    8

    SplitViewNavigatorthe Splitviewnavigator component allows you to create tablet experiences with an easily recognizable mobile ui paradigm. the Splitviewnavigator allows you to have side-by-side content in the landscape ori-entation, and the sidebar is hidden in portrait orientation.

    function getSidebarView() { var viewHTML = + Push Sidebar View + Pop Sidebar View + Push Body View + Pop Body View + ; return { title: Sidebar + parseInt( Math.random() * 100 ).toString(), backLabel: Back, view: $(viewHTML) }; } function pushSidebarView() { window.splitViewNavigator.pushSidebarView( getSidebarView() ); }

  • no software is ever bug-free. if you encounter an issue, have feedback, or have feature requests, please log them at: https://github.com/triceam/app-ui/issues or fork it, fix it, and send me a pull re-quest.

    you can see this framework in the following real-world apps:

    US Census Browser:

    http://itunes.apple.com/us/app/us-census-browser/id483201717?mt=8

    http://tricedesigns.com/census

    get started with appiui today! Just browse to http://triceam.github.com/app-UI/, read the details, download a copy, and start building your own apps!

    if youre building something cool with it, then let me know! id love to hear about it.

    downloAd And contribute

    MORE INFORMATION> >

    SlidingViewthe Slidingview allows content to slide to the side using a horizontal swipe gesture, revealing a naviga-tion container underneath. this is very similar to the behavior in facebooks ipad application. Just swipe horizontally with a finger:

  • appliness( APPLINESS FOCUS GROUP

    HTML5 MULTIMEDIA COMPONENTSPART I: OVERVIEW iAn Devlin, the AuthoR of html5 multimeDiA: Develop AnD DeSign ex-plAinS how to uSe the html5 viDeo AnD AuDio elementS, AnD how to cRe-Ate cuStom plAyBAck componentS.

    interview of iAn devlin

    Hi Ian. Youve been working on web tech-nologies for more than 10 years. Can you in-troduce yourself to our readers?

    hi michael and thanks. well i havent always worked with web technologies as i initially start-ed off as a software developer for a speech recognition company where i was working with the c programming language. During my time at that company i did become interested in web technologies though, as we were creat-ing team intranet sites and i was a part of that. it led me to look for a more web development role for my next job (after being made redun-dant) and i ended up working for the games company Jagex as a web developer working with Java and of course html, cSS and Java-Script. i then (erroneously) moved away from web development for a short while before re-alising that it was where i wanted to be and ive been doing it ever since. i first became interested in html5 at the end of 2009, and have been using it since then. i was also lucky

    enough to write a book on html5 multimedia with peachpit.

    What are you currently working on?

    nothing special to be hon-est. ive o n l y recent- l y moved t o germa- n y so ive b e e n concen-t ra t ing on set-tling in here and trying to i m p r o v e my german. that said, i did find the time to redesign my

  • website, including a custom built wordpress theme (based on html5 Starkers though which sped up the process!). in addition my job re-quires learning some new technologies such as typo3 which is used a lot in germany so i have that to do too. i am trying to find some personal project to work on though, so if any-one needs a co-conspirator...

    Youre a recognized HTML5 expert, especial-ly when it deals with Multimedia elements such as video and audio. Why did you focus on this topic?

    it happened by accident! i curate for html5 gallery and peachpit, now my publisher, who were looking for someone to write a book on html5 multimedia and they approached us. writing a book was something i had never thought about doing before but i thought that this would be a good opportunity so i went for it. i knew the basics of using html5 multimedia already of course, but there were other related topics that i had to learn in order to be able to write about them. this was ideal though as i would read about something, test it, and then write about it in an orderly fashion while it was still fresh in my mind. So it wasnt planned and i focused on it as i had a book to write!

    Apple encouraged the use of the HTML5 vid-eo tag when they launched devices without Flash. What has evolved since this position-ing that happened 2 years ago? Do you feel that HTML5 is rapidly growing and evolving to broadcast multimedia content?

    i think a lot of developers were already aware of html5 multimedia and the and elements, but Apples announcement probably increased this number (of develop-ers) but also brought it to the attention of non-developers who suddenly had to find another method of delivering video and audio to Apple devices. A number of related JavaScript Apis which utilise html5 multimedia are currently being developed that allow more advanced audio manipulation and also the ability to ac-cess a devices web cam (e.g. opera have re-

    leased a demo of this). eventually it will prob-ably be possible to have video conferencing in the browser using html5 alone.

    In your opinion, what should be improved in the current HTML5 specifications for multi-media content?

    the issue of DRm is a big one for some com-panies who have a business requirement for protected content. not everyone agrees with this requirement, but i feel thats a moot point as you wont change that mindset for a long time. this has restricted these big companies from using html5 multimedia and i think that something to facilitate these companies re-quirements should be added. that said, there is currently a proposal to explore this topic and potentially either add it to the html5 specifi-cation or create a separate but related speci-fication that supports it. whether you agree with DRm or not, its addition would increase take up.

    Do you have in mind an amazing HTML5 mul-timedia experience that we could share with the readers?

    i dont know about amazing, but i think there will come a time when the afformentioned vid-eo conferencing with configurable sound and automatic subtitles (if required) will be possi-ble and quite useful. html5 already helps with subtitles via webvtt and i think itll be possi-ble to either have someone translating on the fly (in the same way subtitles are added to live tv programmes) and entering values that way. with some of the sound Apis being worked on, browser games and videos in general should hopefully be able to take advantage of all the capabilities of advanced sound systems (e.g., surround sound) through the browser.

    You blog, you also wrote a book... Would you say that sharing your knowledge is essential for you and for developers in general?

    Sharing knowledge is not essential, but def-initely very useful. i cant count the number

  • of times ive come across a problem, gone to google and found that others have had the exact same issue and solved it. even if the so-lution isnt presented, blog and forum posts can lead to discussions that will set you on the right track, or even off on a tangent to creat-ing something else. As web develoeprs were constantly learning, especially from each other.

    Im a big fan of the music band called Justice. Now that we get the Audio and the Video elements in HTML5, should we get the Disco tag pretty soon?

    my first thought on reading that was that it would be similar to the tag that was deprecated in html5! id envision it taking a number of images and flashing them to the screen with various filters...and that cant be a good thing!

    Interview by Michal Chaize

    HTML5 Multime-dia: Develop and Design

    By Ian Devlin

    One of the most exciting and talked about aspects of the HTML5 specification is the in-troduction of in-browser mul-timedia. Websites no longer have to rely on a third-party tool such as Flash or Silverlight to play video and audio. This book is an easy, approachable guide to building native HTML5 multimedia into a website,

    from the simplest addition to more advanced features. Its written in a simple, straightforward style thats not too techy, yet advanced enough for the more experienced coder who just needs to get up to speed on these powerful new capabilities. The books companion website provides all the examples in a working format for easy ac-cess and enhanced visualization for the reader.

    topics include:- using Audio: how to