Appliness #5 – August 2012

114

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 #5 – August 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 5th issue of this magazine.

    TABLE OF CONTENTS

    NEWS ABOuT HTML AND jAVASCRIPTby Brian Rinaldi

    HELTER SKELTER NEWS

    WHOS BEHIND THE MAGAZINE

    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

    TUTORIALS

    WORkING WITH FILES IN jAVASCRIPT - THE BASICSby Nicholas C. Zakas

    WORkING WITH FILES IN jAVASCRIPT - ADVANCED FEATuRESby Nicholas C. Zakas

    $SCRIPT.jS VS REquIREjS: DEPENDENCy MANAGEMENT COMPARISONSby Joe Zimmerman

    uPDATING NEWS ITEMS DyNAMICALLy by Raymond Camden

    kEy PRINCIPLES OF MAINTAINABLE jAVASCRIPT by Jonathan Creamer

    SOCIAL SHARING THAT SuCkS LESS WITH SOCIALITE.jS by Brian Rinaldi

    TREATING jAVASCRIPT LIkE A 30 yEAR OLD LANGuAGE by Jeremy Khan

    LOCALSTORAGE ExAMPLE: STORING PREVIOuS SEARCHES by Raymond Camden

    uSING SEMANTIC HTML by Terry Ryan

    ExAMPLE OF FORM VALIDATION IN A jquERy MOBILE APPLICATION by Raymond Camden

    INTERVIEW

    PAuL IRISH - THE HTML5 HERO Exclusive interview by Maile Valentine & Michal Chaize

    CHEAT SHEET

    jAVASCRIPT STRING METHODS REFERENCEby Louis Lazaris

    WHATS NEW IN PHONEGAP 2.0 ?by Colene Chow

    PHONEGAP OPEN SOuRCE SAMPLESby Christophe Coenraets and Andy Trice

    FAST PHONEGAP DEVELOPMENT FOR ANDROID WITH APPLAuDby Holly Schinsky

    INTERVIEW OF jOSHFIRE - THE PHONEGAP & WEB MASTERSby Michal Chaize

    SHOWCASE

    BBC OLyMPICSby BBC & Adobe

    GETTING STARTED - VIDEO TuTORIALSby Piotr Walczyszyn

    FOCUS ON PHONEGAP

    EDGE ANIMATIONS AS COMPONENTS by Andy Trice

  • appliness( DONT WORRy, BE APPLI

    by Nicholas C. Zakas

    Playground

    - HTML5

    - JavaScript

    - File System

    Difficulty- rookie- intermediate

    - expert

    Todo list- parse- read- consume

    WORkING WITH FILES IN jAVASCRIPT - THE BASICSMaNy years ago, I was asked durINg a job INtervIew at google what ChaNges I would Make to the web IN order to provIde better experIeNCes. at the top of My lIst was hav-INg soMe way to work wIth fIles other thaN the CoNtrol. thaNkfully, wIth htMl5 aNd related apIs, we Now have far More optIoNs for workINg wIth fIles thaN ever before IN the latest versIoNs of desktop browsers.

    the file type

    the File type is defined in the file apI specification and is an abstract representation of a file. each in-stance of file has several properties:

    - name the filename - size the size of the file in bytes - type the MIMe type for the filea File object basically gives you essential information about the file without providing direct access to the file contents. thats important because reading from files requires disk access, and depending on the size of the file, that process has the potential to take a significant amount of time. a File object is just a reference to a file, and getting data from that file is a separate process altogether.

  • getting file references

    of course, access to user files is strictly forbidden on the web because its a very obvious security issue. you wouldnt want to load up a web page and then have it scan your hard drive and figure out whats there. you need permission from the user in order to access files from their computer. theres no need for messy permission windows, however, because users grant permission for web pages to read files all the time when they decide to upload something.

    when you use a control, youre giving the web page (and the server) permission to access that file. so it makes sense that the first place you can retrieve file objects is through a control.htMl5 defines a files property for all controls. this collection is a FileList, which is an array-like structure called filelist containing file objects for each selected file in the control (remember, HTML5 allows multiple file selection in these controls). so at any point in time, you can get access to the files a user has selected using code similar to this:

    var control = document.getElementById(your-files);control.addEventListener(change, function(event) {

    // When the control has changed, there are new files

    var i = 0, files = control.files, len = files.length;

    for (; i < len; i++) { console.log(Filename: + files[i].name); console.log(Type: + files[i].type); console.log(Size: + files[i].size + bytes); }

    }, false);

    this relatively simple code listens for the change event on the file control. when the event fires, it signi-fies that the file selection has changed, and the code iterates through each file object and outputs its information. keep in mind that the files property is always accessible from javascript, so you dont have to wait for change to try to read it.

    drag and drop files

    accessing files from form controls still requires the form control and the associated user action of brows-ing to find the files of interest. fortunately, htMl5 drag and drop provides another way for users to grant access to their files: by simply dragging a file from the desktop into the web browser. all you have to do to take advantage is listen for two events.

    In order to read files that are dropped onto an area of the page, you must listen for the dragover and drop events and cancel the default action of both. doing so tells the browser that you are handling the action directly and it shouldnt, for example, open an image file.

    2/8

  • var target = document.getElementById(your-files);

    target.addEventListener(dragover, function(event) { event.preventDefault();}, false);

    target.addEventListener(drop, function(event) {

    // cancel default actions event.preventDefault();

    var i = 0, files = event.dataTransfer.files, len = files.length;

    for (; i < len; i++) { console.log(Filename: + files[i].name); console.log(Type: + files[i].type); console.log(Size: + files[i].size + bytes); }

    }, false);

    the event.dataTransfer.files is another filelist object that you can access to get file information. the code is almost exactly the same as using the file form control and the file objects can be accessed in the same way.

    ajax file upload

    once you have a reference to the file, youre able to do something thats pretty cool: upload a file via ajax. this is all possible due to the formdata object, which is defined in xMlhttprequest level 2. this object represents an htMl form and allows you to add key-value pairs to be submitted to the server via the append() method:

    var form = new FormData();form.append(name, Nicholas);

    the great thing about the formdata object is that you can add a file directly to it, effectively mimicking a file upload by htMl form. all you have to do is add the File reference with a specific name, and the browser does the rest. for example:

    // create a form with a couple of valuesvar form = new FormData();form.append(name, Nicholas);form.append(photo, control.files[0]);

    // send via XHR - look ma, no headers being set!var xhr = new XMLHttpRequest();xhr.onload = function() { 3/8

  • console.log(Upload complete.);};xhr.open(post, /entrypoint, true);xhr.send(form);

    once the formdata object is passed into send(), the proper http headers are automatically set for you. you dont have to worry about setting the correct form encoding when using files, so the server gets to act as if a regular htMl form has been submitted, reading file data from the photo key and text data from the name key. this gives you the freedom to write processing code on the backend that can eas-ily work with both traditional htMl forms and ajax forms of this nature.

    and all of this works in the most recent version of every browser, including Internet explorer 10.

    the filereader type

    the FileReader type has a single job: to read data from a file and store it in a javascript variable. the apI is intentionally designed to be similar to xMlhttprequest since both are loading data from an exter-nal (outside of the browser) resource. the read is done asynchronously so as not to block the browser.

    there are several formats that a FileReader can create to represent the file data, and the format must be requested when asking the file to be read. reading is done through calling one of these methods:

    - readAsText() returns the file contents as plain text - readAsBinaryString() returns the file contents as a string of encoded binary data (deprecated use readasarraybuffer() instead)

    - readAsArrayBuffer() returns the file contents as an arraybuffer (good for binary data such as im-ages)

    - readAsDataURL() returns the file contents as a data urleach of these methods initiates a file read similar to the xhr objects send() method initiating an http request. as such, you must listen for the load event before starting to read. the result of the read is al-ways represented by event.target.result. for example:var reader = new FileReader();reader.onload = function(event) { var contents = event.target.result; console.log(File contents: + contents);};

    reader.onerror = function(event) { console.error(File could not be read! Code + event.target.error.code);};

    reader.readAsText(file);

    this example simply reads the contents of a file and outputs it in plain text to the console. the onload handler is called when the file is successfully read whereas the onerror handler is called if the file wasnt read for some reason. the FileReader instance is available inside of the event handler via event.tar-get and its recommended to use that instead of referencing the reader variable directly. the result property contains the file contents on success and error contains error information about the failed op-eration.

    4/8

  • reading data uris

    you can use the same basic setup for reading to a data urI. data urIs (sometimes called data urls) are an interesting option if you want to, for example, display an image that was just read from disk. you could do so with the following code:

    var reader = new FileReader();reader.onload = function(event) { var dataUri = event.target.result, img = document.createElement(img);

    img.src = dataUri; document.body.appendChild(img);};

    reader.onerror = function(event) { console.error(File could not be read! Code + event.target.error.code);};

    reader.readAsDataURL(file);

    this code simply inserts an image that was read from disk into a page. since the data urI contains all of the image data, it can be passed directly into the src attribute of an image and displayed on the page. you could, alternately, load the image and draw it onto a as well:var reader = new FileReader();reader.onload = function(event) { var dataUri = event.target.result, context = document.getElementById(mycanvas).getContext(2d), img = new Image();

    // wait until the image has been fully processed img.onload = function() { context.drawImage(img, 100, 100); }; img.src = dataUri;};

    reader.onerror = function(event) { console.error(File could not be read! Code + event.target.error.code);};

    reader.readAsDataURL(file);

    this code loads the image data into a new Image object and then uses that to draw the image onto a canvas (specifying both the width and height as 100).

    data urIs are generally used for this purpose, but can be used on any type of the file. the most common use case for reading a file into a data urI is to display the file contents on a web page immediately.

    5/8

  • reading arraybuffers

    the arraybuffer type was first introduced as part of webgl. an ArrayBuffer represents a finite num-ber of bytes that may be used to store numbers of any size. the way data is read from an ArrayBuffer is by using a specific view, such as Int8Array, which treats the underlying bytes as a collection of 8-bit signed integers or float32array, which treats the underlying bytes as a collection of 32-bit floating point numbers. these are called typed arrays, which force you to work with a specific numeric type rather than containing any type of data (as with traditional arrays).

    you use an ArrayBuffer primarily when dealing with binary files, to have more fine-grained control over the data. Its beyond the scope of this post to explain all the ins and outs of ArrayBuffer, just realize that you can read a file into an ArrayBuffer pretty easily if you need it. you can pass an ArrayBuffer directly into an xhr objects send() method to send the raw data to the server (youll have to read this data from the request on the server to reconstruct the file), so long as your browser fully supports xMlhttprequest level 2 (most recent browsers, including Internet explorer 10 and opera 12).

    progress events

    progress events are becoming so common that theyre actually written up in a separate specification. these events are designed to generically indicate the progress of data transfers. such transfers occur when re-questing data from the server, but also when requesting data from disk, which is what FileReader does.there are six progress events:

    - loadstart indicates that the process of loading data has begun. this event always fires first. - progress fires multiple times as data is being loaded, giving access to intermediate data. - error fires when loading has failed. - abort fires when data loading has been canceled by calling abort() (available on both xMlhttpre-quest and filereader).

    - load fires only when all data has been successfully read. - loadend fires when the object has finished transferring data. always fires and will always fire after error, abort, or load.

    tracking progress

    when you want to track progress of a file reader, use the progress event. the event object for this event contains three properties to monitor the data being transferred:

    - lengthComputable a boolean indicating if the browser can determine the complete size of the data.

    - loaded the number of bytes that have been read already. - total the total number of bytes to be read.the intent of this data is to allow for progress bars to be generated using the information from the prog-ress event. for example, you may be using an htMl5 element to monitor the progress of reading a file. you can tie the progress value to the actual data using code like this:

    6/8

  • var reader = new FileReader(), progressNode = document.getElementById(my-progress);

    reader.onprogress = function(event) { if (event.lengthComputable) { progressNode.max = event.total; progressNode.value = event.loaded; }};

    reader.onloadend = function(event) { var contents = event.target.result, error = event.target.error;

    if (error != null) { console.error(File could not be read! Code + error.code); } else { progressNode.max = 1; progressNode.value = 1; console.log(Contents: + contents); }};

    reader.readAsText(file);

    this is similar to the approach that gmail uses for its drag and drop file upload implementation, where you see a progressbar immediately after dropping a file onto the email. that progressbar indicates how much of the files has been transferred to the server.

    dealing with errors

    even though youre reading a local file, its still possible for the read to fail. the file apI specification de-fines four types of errors:

    - NotFoundError the file cant be found.- SecurityError something about the file or the read is dangerous. the browser has some leeway as to when this occurs, but generally if the file is dangerous to load into the browser or the browser has been performing too many reads, youll see this error.

    - NotReadableError the file exists but cant be read, most likely due to a permissions problem.- EncodingError primarily when trying to read as a data urI and the length of the resulting data urI is beyond the maximum length supported by the browser.

    when an error occurs during a file read, the FileReader objects error property is assigned to be an instance of one of the above mentioned errors. at least, thats how the spec is written. In reality, brows-ers implement this as a FileError object that has a code property indicating the type of error that has occurred. each error type is represented by a numeric constant value:

    - FileError.NOT_FOUND_ERR for file not found errors.- FileError.SECURITY_ERR for security errors.- FileError.NOT_READABLE_ERR for not readable errors.

    7/8

  • 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 ya-hoo! homepage and a contributor to the yuI library. he is the author of Maintainable javascript (oreilly, 2012), professional javascript for web developers (wrox, 2012), high performance javascript(oreilly, 2010), and professional ajax (wrox, 2007)http://www.nczonline.net/

    @slicknet

    His bloghttp://www.nczonline.net/

    His GitHub repositoryhttps://github.com/nzakas/

    His bookshttp://www.nczonline.net/writing/

    ONLINE RESOURCES

    - FileError.ENCODING_ERR for encoding errors.- FileError.ABORT_ERR when abort() is called while there is no read in progress.you can test for the type of error either during the error event or during loadend:

    var reader = new FileReader();

    reader.onloadend = function(event) { var contents = event.target.result, error = event.target.error;

    if (error != null) { switch (error.code) { case error.ENCODING_ERR: console.error(Encoding error!); break;

    case error.NOT_FOUND_ERR: console.error(File not found!); break;

    case error.NOT_READABLE_ERR: console.error(File could not be read!); break;

    case error.SECURITY_ERR: console.error(Security issue with file!); break;

    default: console.error(I have no idea whats wrong!); } } else { progressNode.max = 1; progressNode.value = 1; console.log(Contents: + contents); }};

    reader.readAsText(file);

  • appliness( DONT WORRy, BE APPLI

    by Nicholas C. Zakas

    Playground

    - Files

    - Array

    - JavaScript

    Difficulty- rookie- intermediate

    - expert

    Todo list- write- async- master

    WORkING WITH FILES IN jAVASCRIPT - ADVANCED FEATuRESIN the prevIous artICle, youve learNed how to use fIles IN the tradItIoNal way. you CaN upload fIles to the server aNd you CaN read fIle data froM dIsk. these all represeNt the Most CoMMoN ways of dealINg wIth fIles. however, there Is a CoMpletely New way to deal wIth fIles that has the CapaCIty to sIMplIfy soMe CoMMoN tasks. thIs New way Is to use objeCt urls.

    what is an object url?

    object urls are urls that point to files on disk. suppose, for example, that you want to display an im-age from the users system on a web page. the server never needs to know about the file, so theres no need to upload it. you just want to load the file into a page.

    you could, as shown in the previous posts, get a reference to a file object, read the data into a data urI, and then assign the data urI to an element. but think of all the waste: the image already exists on disk, why read the image into another format in order to use it?

    If you create an object url, you could assign that to the and access that local file directly.

  • how does it work?

    the file apI defines a global object called url that has two methods. the first is createObjectURL(), which accepts a reference to a file and returns an object url. this instructs the browser to create and manage a url to the local file. the second method is revokeObjectURL(), which instructs the browser to destroy the url that is passed into it, effectively freeing up memory. of course, all object urls are revoked once the web page is unloaded, but its good to free them up when theyre no longer needed anyway.

    support for the url object isnt as good as for other parts of the file apI. as of the time of my writing, Internet explorer 10+ and firefox 9+ support a global url object. Chrome supports it in the form of web-kiturl while safari and opera have no support.

    example

    so how would you display an image from disk without reading the data first? suppose that youve given the user a way to select a file and now have a reference to it in a variable called file. you can then use the following:

    var URL = window.URL || window.webkitURL, imageUrl, image;

    if (URL) { imageUrl = URL.createObjectURL(file); image = document.createElement(img);

    image.onload = function() { URL.revokeObjectURL(imageUrl); };

    image.src = imageUrl; document.body.appendChild(image);}

    this example creates a local url variable that normalizes the browser implementations. assuming that url is supported, the code goes on to create an object url directly from file and stores it in imageUrl. a new element is created and given an onload event handler that revokes the object url (more on that in a minute). then, the src property is assigned to the object url and the element is added to the page (you may want to use an already-existing image).

    why revoke the object url once the image is loaded? after the image is loaded, the url is no longer needed unless you intend to reuse it with another element. In this example, the image is being loaded into a single element, and once the image has been completely loaded, the url isnt serving any useful purpose. thats the perfect time to free up any memory associated with it.

    2/5

  • security and other considerations

    at first glance, this capability is a bit scary. youre actually loading a file directly from the users machine via a url. there are, of course, security implications to this capability. the url itself isnt a big security issue because its a url thats assigned dynamically by the browser and would be useless on any other computer. what about cross-origin?

    the file apI disallows using object urls on different origins. when an object url is created, it is tied to the origin of the page in which the javascript executed, so you cant use an object url from www.wrox.com on a page at p2p.wrox.com (an error occurs). however, two pages from www.wrox.com, where one is embedded in the other with an iframe, are capable of sharing object urls.

    object urls exist only so long as the document that created them. when the document is unloaded, all object urls are revoked. so, it doesnt make sense to store object urls in client-side data storage to use later; they are useless after the page has been unloaded.

    you can use object urls anywhere the browser would make a get request, which includes images, scripts, web workers, style sheets, audio, and video. you can never use an object url when the browser would perform a post, such as within a whose method is set to post.the file object is actually a more specific version of a blob, which represents a chunk of binary data. the size and type properties exist on blob objects and are inherited by file.

    In most cases, blobs and files can be used in the same places. for example, you can read from a blob using a filereader and you can create an object url from a blob using url.createobjecturl().

    slicing

    one of the interesting things you can do with blobs (and therefore, also files) is to create a new blob based on a subsection of another one. since each blob just represents pointers to data rather than the data itself, you can quickly create new blob objects pointing to subparts of others. this is accomplished by using the slice() method.you may be familiar with slice() on strings and arrays, and the one for blobs behaves in a similar man-ner. the method accepts three arguments: the offset of the starting byte, the offset of the ending byte, and an optional MIMe type to apply to the blob. If the MIMe type isnt specified, the new blob has the same MIMe type as the original one.

    browser support for slice() isnt yet ubiquitous, with firefox supporting it via mozSlice() and web-kitSlice() in Chrome (no other browsers support this method currently). heres an example:function sliceBlob(blob, start, end, type) {

    type = type || blob.type;

    if (blob.mozSlice) { return blob.mozSlice(start, end, type); } else if (blob.webkitSlice) { return blob.webkitSlice(start, end type); } else { throw new Error(This doesnt work!); }}

    3/5

  • you can then use this function to, for example, split up a large file to upload it in chunks. each new blob being produced is independent from the original even though the data each references has an overlap. the engineers at flickr use blob slicing to read the exif information from photos that are uploaded rather than waiting to it on the server. when the file is selected, the flickr upload page simultaneously starts to upload the file as well as read the exif information from the photo. this allows them to give a preview of the extracted metadata in the page as the file is being uploaded.

    creating blobs the old way

    very soon after file objects started appearing in browsers, developers realized that blob objects were ac-tually quite powerful and so wanted to be able to create them without user interaction. after all, any data can be represented in a blob, it doesnt necessarily have to be tied to a file. browsers quickly responded by creating BlobBuilder, a type whose sole purpose is to wrap some data in a blob object. this is a non-standard type and has been implemented in firefox (as MozBlobBuilder), Internet explorer 10 (as MSBlobBuilder), and Chrome (as WebKitBlobBuilder).the BlobBuilder works by creating a new instance and calling the append() method with a string, arraybuffer, or blob. once all of the data has been added, you call getBlob() and pass in an optional MIMe type that should be applied to blob. heres an example:

    var builder = new BlobBuilder();builder.append(Hello world!);var blob = builder.getBlob(text/plain);

    the ability to create urls for arbitrary pieces of data is incredibly powerful, allowing you to dynamically create objects that can be addressed as files in the browser. you could, for example, use a blob to create a web worker without having a separate file for the worker code. this technique was written up in the basics of web workers:

    var bb = new BlobBuilder();bb.append(onmessage = function(e) { postMessage(msg from worker); });

    // Obtain a blob URL reference to our worker file.// Note: window.webkitURL.createObjectURL() in Chrome 10+.var blobURL = window.URL.createObjectURL(bb.getBlob());

    var worker = new Worker(blobURL);worker.onmessage = function(e) { // e.data == msg from worker};worker.postMessage(); // Start the worker.

    this code creates a simple script and then creates an object url. the object url is assigned to a web worker in place of a script url.

    you can call append() as many times as you like, building up the contents of the blob.

    4/5

  • 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 ya-hoo! homepage and a contributor to the yuI library. he is the author of Maintainable javascript (oreilly, 2012), professional javascript for web developers (wrox, 2012), high performance javascript(oreilly, 2010), and professional ajax (wrox, 2007)http://www.nczonline.net/

    @slicknet

    His bloghttp://www.nczonline.net/

    His GitHub repositoryhttps://github.com/nzakas/

    His bookshttp://www.nczonline.net/writing/

    ONLINE RESOURCES

    creating blobs the new way

    because developers kept clamoring for a way to create blob objects directly, and browsers coming up with BlobBuilder, it was decided to add a blob constructor. this constructor is now part of the speci-fication and will be the way that blob objects are created in the future.

    the constructor accepts two arguments. the first is an array of parts to combine into a blob. these would be the same values as passed into the append() method of blobbuilder and can be any number of strings, blobs, and ArrayBuffers. the second argument is an object containing properties for the newly-created blob. there are currently two properties defined, type, which specifies the MIMe type of the blob, and endings, which can be either transparent (default) or native. heres an example:

    var blob = new Blob([Hello world!], { type: text/plain });

    as you can see, this is much simpler than using BlobBuilder.the blob constructor is currently in the nightly builds of Chrome and will be in firefox 13. other brows-ers have not yet announced plans to implement this constructor, however, it is now part of the file apI standard and is expected to be implemented universally.

    conclusion

    this is the last part of the series on working with files in javascript. as I hope you learned, the file apI is incredibly powerful and opens up entirely new ways of working with files in web applications. you no longer need to stick with plain file upload boxes when users need to upload files, and now that you can read the files in the client, that opens up all sorts of possibilities for client-side manipulation. you could resize an image thats too large before uploading (using FileReader and ); you could create a text editor that works purely in the browser; you could split up large files to upload piece by piece. the possibilities arent quite endless, but are pretty damn close.

  • appliness( DONT WORRy, BE APPLI

    by joe Zimmerman

    Playground

    - $script.js

    - RequireJS

    - jquery.js

    Difficulty- rookie- intermediate

    - expert

    Todo list- load- run- execute

    $SCRIPT.jS VS REquIREjS: DEPENDENCy MANAGEMENT COMPARISONSas javasCrIpt Moves further aNd further away froM the playgrouNd prograMMINg laN-guage that It used to be, aNd Is used More aNd More as the Core for large-sCale applI-CatIoNs, MaNagINg the Code starts to beCoMe extreMely dIffICult. splIttINg the Code INto MultIple fIles helps wIth that, though It also adds More CoMplexIty IN a dIffereNt way. oNe way to fIght thIs New CoMplexIty Is wIth depeNdeNCy MaNageMeNt lIbrarIes, but whICh oNe Is rIght for you?

    script loading vs dependency management

    the two libraries mentioned in the title $script.js and requirejs are not technically classified in the same way because though they do similar things, they have different emphasis. $script.js is a script loader with dependency management, and while requirejs is the same way, its dependency management is much more powerful and more closely resembles what you would use for importing classes in compiled languages such as java. youll see what I mean soon.

  • $script.js

    this handy library was created by dustin diaz and jacob thornton and is hosted on github. thats where youll find the documentation on how to use it, but Ill still show it off a bit here to give you an idea of how it works. Ive actually already written an article about this library which happens to be the first post ever on this blog but its focus was quite different.

    first, well talk about the most basic usage: loading a script.

    $script(jquery.js);

    this loads jquery.js asynchronously onto the page. this is no more useful than just using a normal script tag though. Its slightly shorter, but since it is loaded asynchronously, the code right after this line will run before jquery.js is loaded. so, we also give it a callback function that runs after jquery.js is loaded.

    $script(jquery.js, function() { // do stuff with jQuery.});

    Now, once jquery.js is loaded and executed, well be sure that we can access the objects and functions that it defines. there is so much more you can do with $script.js including named dependencies but this gives you the gist of how to use it. with this, weve successfully defined a dependency and assured the dependency would be loaded and executed before we tried to use it. using something like this al-lows us to only need to use 2 script tags in our htMl (one to load $script.js and one to load the main application). the rest of the scripts that we depend on can be managed with $script.js.

    requirejs

    requirejs is a much larger project, with a github project and a site of its own. youll find the documen-tation for requirejs at that second link, but if you want to read some history and a more thorough intro-duction to requirejs you can read this article on adobe developer Connection.

    requirejs can be use almost exactly like $script.js to load plain javascript files, but its so much more powerful than that. you can define modules, and then load those module dependencies in without ex-posing them globally, so that every bit of your code can be safe from 3rd party scripts. take a look.

    first well just define a module that can pulled in as a dependency.

    // This is just an object literaldefine({ name: Joe Zim, gender: male}); // Heres a constructor so you can create// new objects, rather than just the one// literal objectdefine(function() { var Person = function( name, gender ) { this.name = name; this.gender = gender; }; 2/4

  • return Person;} );

    you can see two different types of modules there. the first one is just defined as an object literal, which will be what is returned to the dependent script, as youll see later. the second example has a function, which will be run immediately when the module is loaded as a dependency and the value that is returned from that function will be the value that is given to the dependent script.

    Now well create a module that is dependent on the module we just defined. well assume that the mod-ule above is saved as person.js. heres how we define another module that is dependent on the module we just made, plus another module that was created behind the scenes.

    define( [ person, list], function( Person, List ) { var personList = new List( new Person(Joe Zim, male); ); return personList;} );

    we define the module exactly as we did before, except this time we send in an array as the first param-eter. the array lists strings of file names (sans the .js) of modules to fetch. then, when those modules are fully loaded, they are sent in as parameters to the function for the new module you are defining. as stated above, this localizes the modules so they are not accessible globally.

    Now well write a bit of code that is dependent on the latest module and the person module, but isnt creating a new module. well assume that the latest created module is saved as default-person-list.js.

    require( [ default-person-list, person], function( list, Person ) { var chuck = new Person( Chuck Norris, male ); list.addItem( chuck ); list.forEach( function( item ) { alert(item.name); } );} );

    this is almost exactly the same as creating a module that is dependent on another module except for a couple important things:

    1. we no longer use the define function; instead we use require (finally we know where the name of the library comes from!).

    2. theres no need to return anything from the function. since this is not being defined as a module, it is just run as is and therefore has no need to return anything.

    thats the gist of requirejs, but theres one more thing thats pretty important to note about requirejs. It comes with a build tool that will look through all of the modules and other javascript files and concat-enate and minify them so that even though you spent all that time create separate files, it wont become a performance problem.

    3/4

  • ABOUT THIS ARTICLE

    joe Zimmerman has been doing web development for 12 years, which may make him sound old, but since he started in middle school, hes still pretty young. htMl and Css were the coolest inventions ever. In college he was introduced to real javascript, starting his full addiction. Now his addiction push-es him to continuously learn more and spread the knowledge to the internet.http://www.joezimjs.com/

    @joezimjs

    Script.js Githubhttps://github.com/ded/script.js

    RequireJS Githubhttps://github.com/jrburke/requirejs

    RequireJS Websitehttp://www.requirejs.org/

    ONLINE RESOURCES

    whats right for you?

    If you are a very modular programmer and you enjoy the idea of keeping the modules localized, then taking the requirejs route is probably a really good idea for you. If your application is relatively simple or you just dont like the idea of converting everything into individual module files, then something like $script.js would probably be a great fit. ultimately its up to you, as they are both great tools. anyway, thats all for today; happy coding and god bless!

  • appliness( DONT WORRy, BE APPLI

    by raymond Camden

    Playground

    - Caching

    - HTML5

    - ColdFusion

    Difficulty- rookie- intermediate

    - expert

    Todo list- get data- save- retrive

    uPDATING NEWS ITEMS DyNAMICALLyrayMoNd CaMdeN has beeN workINg oN a Cool proof of CoNCept. the Idea Is to repro-duCe the behavIor of the faCebook News feed aNd add soMe features.

    goals of this proof of concept

    I apologize in advance if the title of this article isnt terribly clear. for a while now Ive wanted to build a proof of concept javascript application that demonstrated automatically displaying new content. think of your facebook news feed as an example. In a trivial application, you could simply get your new content and prepend it to the content. however, I wanted to do something a bit more complex.

    first - I wanted to gracefully display the new content via animation. so instead of simply popping in, you can see it slide in and push the older content down.

    secondly - and this is a bit of a pet peeve of mine, I wanted to make the application not shift the content when

    a) Im mouseovered the text or when

    b) Ive scrolled down a bit to focus in one one particular news item.

    why?

    well, for the first item, I cant tell you how many times Ive been about to click something in tweetdeck when the app decides to scroll down content when new stuff is loaded. Its very annoying. as for the second item, Ill often find myself reading some-thing when the feed decides to update. again - annoying.

  • so lets start off with a first draft of the application. In this version, Ill run a scheduled process every few seconds or so, get new content (which will just be random), and simply prepend it to my div. heres this version:

    var template;var streamDiv;

    $(document).ready(function() {

    var source = $(#itemTemplate).html(); template = Handlebars.compile(source);

    streamDiv = $(#stream);

    //set up an interval to ask for new data window.setInterval(checkData, 4000);

    Handlebars.registerHelper(dateFormat, function(dt) { return (dt.getMonth()+1) + / + dt.getDate() + / + dt.getFullYear() + + (dt.getHours()+1) + :+dt.getMinutes(); });

    });

    function checkData() { console.log(running checkData); //for now, create 0-3 fake items var newDataSize = Math.floor(Math.random()*3); if(newDataSize === 0) return;

    var data = []; for(var i=0;i

  • {{title}}By: {{author}}Posted: {{dateFormat created}}

    #stream { width: 400px;}

    .item { border: solid black 1px; margin-bottom: 15px; background-color: #e0e0e0;}

    Stream

    Im assuming most of this will be pretty basic for appliness readers. Im making use of handlebars for my display. you can see the template generation first in the document ready block. I set an interval of 4 sec-onds for generating new content.

    My checkData function handles getting the new data. I select a random number of items from 0 to 3. If we have any number over 0, I generate fake news items for each. finally - we take each new item item and prepend it to a div. this is as about as simple as it gets.

    3/9

  • animations

    for my next iteration, I decided to work on the animation. jQuery has a nice animation method called slidedown. given hidden content, you can use this to slowly reveal the content over a duration. here is the modified version for the updated display code:

    data.forEach(function(itm) { var html = template(itm); var domitem = $(html); domitem.hide(); streamDiv.prepend(domitem); domitem.slideDown(slow);});

    this was pretty simple, but has a small bug in it. In any iteration of checkdata, you may have multiple new items added to the stream. with the code above, each one has its own slide effect. when you have 2 items you get a venetian blinds type of effect. while this was wrong, I thought it was kinda cool too:

    I figured that I could fix this by applying the hide/slidedown to a wrapper for all of the new content in any given run of checkdata. I modified the code to create a new div around my N news items and then applied the animation to that:

    data.forEach(function(itm) { html += template(itm);});

    html += ;var domitem = $(html).hide();streamDiv.prepend(domitem);domitem.slideDown(slow);

    4/9

  • this worked better:

    handle mouse events

    woot! ok, so at this point, I thought I had it displaying adequately. Now for the hard part. I wanted to find a way to pause updating when you either mouseovered a news item or scrolled down some. I decided to first worry about the mouse events.

    var template;var streamDiv;var html = ;var hiding = false;var hb;

    $(document).ready(function() {

    var source = $(#itemTemplate).html(); template = Handlebars.compile(source);

    streamDiv = $(#stream); 5/9

  • //set up an interval to ask for new data hb = window.setInterval(checkData, 4000);

    Handlebars.registerHelper(dateFormat, function(dt) { return (dt.getMonth()+1) + / + dt.getDate() + / + dt.getFullYear() + + (dt.getHours()+1) + :+dt.getMinutes(); });

    $(#stream).on(mouseover,.item, function() { console.log(hiding); hiding=true; //console.log($(this).position().top); });

    $(#stream).on(mouseout,.item, function() { console.log(UNhiding,html); hiding=false; addToStream(html); });

    });

    function checkData() { console.log(running checkData); //for now, create 0-3 fake items var newDataSize = Math.floor(Math.random()*3); if(newDataSize === 0) return;

    var data = []; for(var i=0;i

  • }

    {{title}}By: {{author}}Posted: {{dateFormat created}}

    #stream { width: 400px;}

    .item { border: solid black 1px; margin-bottom: 15px; background-color: #e0e0e0; padding: 5px;}

    Stream

    I pasted the entire template since this one has changes in multiple areas. first - note the mouseover/mouseout event handlers. when we mouseover, I update a global variable to indicate we should hide up-dates. when we mouseout, we flip that and run a new method, addtostream. Note that html is now a global variable.

    If you scroll down to checkdata, you can see now that we check the hiding status before we display any-thing. because we have 2 places that need to display html (remember the mouseout event above), I ab-stracted it out into its own method. addtostream simply renders out the items and clears the global html variable.

    scrolling

    ok... still with me? for the final modification, I wanted to make it so that if you had scrolled down (in theory to view a news item), the main stream div would not update. this is rather easy if you listen for scroll event on the window object. however - I also wanted to make this rule have less priority then the mouseover rule. since I only had one global variable (hiding), I needed another flag just for when I had mouseovered content. this code block has the relevant changes. 7/

    9

  • var template;var streamDiv;var html = ;var hiding = false;var hb;var mouseOvered = false;

    $(document).ready(function() {

    var source = $(#itemTemplate).html(); template = Handlebars.compile(source);

    streamDiv = $(#stream);

    //set up an interval to ask for new data hb = window.setInterval(checkData, 4000);

    Handlebars.registerHelper(dateFormat, function(dt) { return (dt.getMonth()+1) + / + dt.getDate() + / + dt.getFullYear() + + (dt.getHours()+1) + :+dt.getMinutes(); });

    $(#stream).on(mouseover,.item, function() { console.log(hiding); hiding=true; mouseOvered=true; //console.log($(this).position().top); });

    $(#stream).on(mouseout,.item, function() { console.log(UNhiding,html); hiding=false; mouseOvered=false; addToStream(html); });

    $(window).on(scroll,function() { //Only care if not mouseOvered if(mouseOvered) return; var scroll = $(window).scrollTop(); if(scroll > 0) hiding = true; else { hiding = false; if(html != ) addToStream(html); } });

    });

    looking at the mouse events, you can see the new variable being set, mouseovered. below them you can see the new handler for scroll events.

    8/9

  • Im not terribly sure how smart this is, but it seems to work ok in my testing:

    you can view the source here:

    https://github.com/michaelchaize/appliness/blob/master/ray%20items/index.html

  • appliness( DONT WORRy, BE APPLI

    by jonathan Creamer

    Playground

    - JavaScript

    - patterns

    - jQuery

    Difficulty- rookie- intermediate

    - expert

    Todo list- comment- organize- cache queries

    kEy PRINCIPLES OF MAINTAINABLE jAVA-SCRIPTjavasCrIpt Is a CurIous laNguage. Its easy to wrIte, but dIffICult to Master. by the eNd of thIs artICle, hopefully, youll traNsforM your spaghettI Code INto a fIve-Course Meal, full of readable, MaINtaINable yuMMINess!

    why is it so tough?

    the thing to remember, above all else when writing js code, is that its a dynamic language. this means there are a lot of ways to do things. you dont have to deal with strongly typed classes, or some of the more complex features from languages, like C# and java. this is both a blessing and a curse.

    the hardness of javascript is clearly evident when considering the following image:

  • the teeny tiny book on the left is douglas Crockfords Must read book, javascript: the good parts. towering next to it, on the right, is, javascript the definitive guide, by david flanagan.

    while both of these books are excellent reads, the good parts illustrates that, although javascript has a lot of stuff in it, the good parts can be summed up in a considerably shorter read. so, if youre looking for a good, quick read, go with the good parts and read it a few times!

    you can read an article on the history of javascript here, but the gist of it is that brandon eich, in 1995,

    T his, naturally, led to a lot of sleepless nights for web de-velopers.

    was hired by Netscape to design a language. what he came up with was the loosely typed language that we know as javascript. over the years, it became stan-dardized as eCMascript, but, throughout all the brows-er wars, the various browsers implemented these fea-tures differently. this, naturally, lead to a lot of sleepless

    nights for web developers. this problem, when combined with the fact that javascript was considered to be most applicable for manipulating images and performing quick bits of validation, led javascript to, incorrectly, be viewed as a terrible language.

    Its time to fix that! while, yes, there are plenty of bad things about javascript, when used properly, it can be a fantastic language and its dynamic nature will grow on you!

    making it better

    Namespaces

    one of the downfalls of how javascript is implemented is that it operates on top of a global object. In the case of browsers, this will wind up being the window object. so, anytime that code like this is present on a page

    function doStuff(){ alert(I am doing stuff);} function doMoreStuff(){ var images = document.images.length; console.log(There are + images + on this page);}doStuff();doMoreStuff();

    the functions doStuff and the doMoreStuff functions are immediately available to the global window object.

    this means that if anyone comes along and attempts to write a function, which is also called, doStuff, there will be a conflict! all script tags are basically taking the code within them, and running it against the window in the order that they are referenced in the htMl. as a result, the second person to imple-ment doStuff will overwrite the first doStuff.

    2/8

  • a common technique for eliminating this problem is to take advantage of either self-executing anony-mous functions, or namespaces. the object-oriented folks reading this are likely already familiar with the concept of a namespace, but the basic idea is to group functions into different areas for re-usability.

    var NS = NS || {}; // If NS is not defined, make it equal to an empty objectNS.Utils = NS.Utils || {};NS.Models = NS.Models || {};NS.Views = NS.Views || {};

    this will prevent pollution of the global namespace, and will aid in readability for your application. Now, you simply define functions in their respective namespace. a commonly defined namespace is app, which manages the rest of the application.

    design patterns and practices

    In every language, there exists a set of design patterns. addy osmani says

    D esign patterns are reusable solutions to commonly occurring problems in software design.there are lots, and, when used correctly, they can greatly impact your applications maintainabilty. addy wrote a great javascript design patterns book, called essential design patterns. absolutely give it a read!

    another commonly used pattern is the Revealing Module Pattern.

    NS.App = (function () { // Initialize the application var init = function () { NS.Utils.log(Application initialized...); }; // Return the public facing methods for the App return { init: init };}()); NS.App.init();

    above, an App function is defined within the NS object. Inside, a function variable for init is defined, and returned as an anonymous object literal. Notice that, at the end, theres that extra set of parenthesis: }());. this forces the NS.App function to automatically execute and return. Now, you can call NS.App.init() to initialize your app.the anonymous function above is a best practice in javascript, and is referred to as a Self-Executing Anonymous Function. because functions in javascript have their own scope i.e. variables defined inside of functions are not available outside of them this makes anonymous functions useful in multiple ways.

    // Wrap your code in a SEAF(function (global) { // Now any variables you declare in here are unavailable outside.

    3/8

  • var somethingPrivate = you cant get to me!; global.somethingPublic = but you can however get to me!; }(window)); console.log(window.somethingPublic); // This works...console.log(somethingPrivate); // Error

    In this example, because this function is automatically executed, you can pass the window in to the exe-cuting part }(window));, and it will be made available as global inside of the anonymous funtion. this practice limits the global variables on the window object, and will assist in preventing naming collisions.Now, you can start using seafs in other areas of your application to make the code feel more modular. this allows for your code to be re-usable, and promotes good separation of concerns.

    heres an example of a potential use for these ideas.

    (function ($) { var welcomeMessage = Welcome to this application! NS.Views.WelcomeScreen = function () { this.welcome = $(#welcome); }; NS.Views.WelcomeScreen.prototype = { showWelcome: function () { this.welcome.html(welcomeMessage) .show(); } };}(jQuery)); $(function () { NS.App.init();}); // Modify the App.init abovevar init = function () { NS.Utils.log(Application initialized...); this.welcome = new NS.Views.WelcomeScreen(); this.welcome.showWelcome();};

    so, above, there are a few different things going on. firstly, jQuery is passed as an argument to the anonymous function. this ensures that the $ is actually jQuery inside of the anonymous function.Next, theres a private variable, called welcomeMessage, and a function is assigned to NS.Views.Wel-comeScreen. Inside this function, this.welcome is assigned to a jQuery doM selector. this caches the selector inside the welcomeScreen, so that jQuery doesnt have to query the doM for it more than once.

    D OM queries can be memor y intensive, so please ensure that you cache them as much as possible.

    4/8

  • Next, we wrap the app init within $(function(){});, which is the same thing as doing $(docu-ment).ready().finally, we add some code to the app initializer. this keeps your code nice and separated, and will be considerably easy to come back to and modify at a later day. More maintainability!

    observer pattern

    another excellent pattern is the observer pattern sometimes referred to as pubsub. pubsub essen-tially allows us to subscribe to doM events, such as click and mouseover. on one hand, were listen-ing to these events, and, on the other, something is publishing those events for example, when the browser publishes (or announces) that someone clicked on a particular element. there are many libraries for pubsub, as its a short bit of code. perform a quick google search, and thousands of choices will make themselves available. one solid choice is amplifyjss implementation.

    // A data model for retrieving news.NS.Models.News = (function () { var newsUrl = /news/ // Retrieve the news var getNews = function () { $.ajax({ url: newsUrl type: get, success: newsRetrieved }); }; var newsRetrieved = function (news) { // Publish the retrieval of the news amplify.publish(news-retrieved, news); }; return { getNews: getNews };}());

    this code defines a model to fetch news from some kind of service. once the news has been retrieved with ajax, the newsRetrieved method fires, passing through the retrieved news to amplify, and is pub-lished on the news-retrieved topic.

    (function () { // Create a news views. NS.Views.News = function () { this.news = $(#news); // Subscribe to the news retrieval event. amplify.subscribe(news-retrieved, $.proxy(this.showNews)); }; // Show the news when it arrives NS.Views.News.prototype.showNews = function (news) { 5/8

  • var self = this; $.each(news, function (article) { self.append(article); }); };}());

    this code above is a view for displaying the retrieved news. In the News constructor, amplify subscribes to the news-retrieved topic. when that topic is published, the showNews function is fired, accordingly. then, the news is appended to the doM.

    // Modify this the App.init abovevar init = function () { NS.Utils.log(Application initialized...); this.welcome = new NS.Views.WelcomeScreen(); this.welcome.showWelcome(); this.news = new NS.Views.News(); // Go get the news! NS.Models.News.getNews();};

    again, modify the init function from the app to add the news retrieval and youre done! Now, there are separate pieces of the application, each of which is responsible for a single action. this is known as the single responsibility principle.

    documentation and files/minification

    one of the keys to maintainable code of any kind not just js is documentation and commenting. Com-ments can serve to be invaluble for new developers coming into a project needing to understand whats occurring in the code. why did I write that one line again?. an excellent tool for generating documen-tation is called, docco. this is the same tool that generates the documentation for the backbone.js web site. basically, it takes your comments, and places them side by side with your code.

    there are also tools, like jsdoc, which generate an apI style documentation, describing every class in your code.

    another thing, which can prove to be difficult when starting a new project, is trying to determine how to best organize your code. one way is to separate pieces of functionality into separate folders. for ex-ample:

    /app.js

    /libs/jquery.js

    /libs/jquery-ui.js

    /users/user.js

    /views/home.js

    this structure helps keep pieces of functionallity apart from one another. there are, of course, several ways to organize code, but all that really matters is deciding on a structure and then rolling with it. Next, you can make use of a build and minification tool. there are lots of choices:

    6/8

  • grunt

    google Closure

    jsMin

    yuI Compressor

    these tools will strip out whitespace, remove comments, and combine all specified files into one. this re-duces the file sizes and http requests for the application. even better, this means that you can keep all of your files separated during development, but combined for production.

    amd

    A synchronous Module Defi-nition is a different way of writing JavaScript code.

    asynchronous Module definition is a different way of writing javascript code; it divides all code into separate modules. aMd creates a standard pattern for writing these modules to load in code asynchronously.

    using script tags blocks the page, as it loads until the doM is ready. therefore, using something like aMd will

    allow the doM to continue loading, while the scripts are also still loading. essentially, each module is di-vided into its own file, and then theres one file that kicks off the process. the most popular implementa-tion of aMd is requirejs.

    // main.jsrequire([libs/jquery,app.js], function ($, app) { $(function () { app.init(); });}); // app.jsdefine([libs/jquery, views/home], function ($, home) { home.showWelcome();}); // home.jsdefine([libs/jquery], function ($) { var home = function () { this.home = $(#home); }; home.prototype.showWelcome = function () { this.home.html(Welcome!); }; return new home();});

    In the code snippet above, there is a main.js file, which is where the process begins. the first argument to the require function is an array of dependencies. these dependencies are a list of files that are re-quired for app.js. as they finish loading, whatever the module returns is passed as an argument to the function callback on the right.

    7/8

  • ABOUT THIS ARTICLE

    jonathan develops front end applications in jQuery and javascript at appendto.com and is a lover of all things web, mostly asp.Net MvC, javascript, jQuery, & C#. he stays active in the .Net world at-tending user groups, blogging for freshbrewed-Code.com & scouring twitter & the interwebs for as much knowledge he can squeeze into his brain. please feel free to contact him, he loves meeting other devs who are passionate about what they do... http://jcreamerlive.com/

    @jcreamer898

    Learning JavaScript Design Patternshttp://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailnamespacing

    AmplifyJS PUB/SUBhttp://amplifyjs.com/api/pubsub/

    Single Responsibility Principlehttp://freshbrewedcode.com/derekgreer/2011/12/08/solid-javas-cript-single-responsibility-principle/

    ONLINE RESOURCES

    then, there is app.js, which requires jQuery, as well as a view. Next, the view, home.js, only requires jQuery. It has a home function within it, and returns an instance of itself. In your application, these mod-ules are all stored within separate files, making your application very maintainable.

    conclusion

    keeping your applications maintainable is extremely important for development. It reduces bugs, and makes the process of fixing ones that you do find easier.

    F riends dont let fr iends write spaghetti code!

  • appliness( DONT WORRy, BE APPLI

    by brian rinaldi

    Playground

    - Twitter

    - Facebook

    - Socialite.js

    Difficulty- rookie- intermediate

    - expert

    Todo list- add buttons- share- socialize

    SOCIAL SHARING THAT SuCkS LESS WITH SO-CIALITE.jSIf you have a CoNteNt sIte lIke a blog, for exaMple, INtegratINg soCIal sharINg buttoNs have beCoMe a NeCessary evIl. doNt get Me wroNg, I eNjoy twItter as MuCh as the Next guy (I tolerate faCebook whIle grudgINgly partICIpate IN lINkedIN aNd soMe others) but ClutterINg your page wIth a varIety of buttoNs for sharINg Is usually aN eye-sore but NeCessary If you waNt people to fINd aNd share your CoNteNt. however, the laCk of vI-sual appeal Is oNly oNe of the poteNtIal probleMs wIth these buttoNs. the other Is that they all rely oN thIrd-party sCrIpts beINg loaded that CaN poteNtIally bloCk the loadINg of your CoNteNt.

    there are a number of articles that document the problem with loading third-party scripts, and Ill cover that topic very briefly here. thankfully though, if you want to quickly and easily add social sharing but-tons to your content without blocking your content, david bushell has created a small javascript library called socialite.js that will help you do this. this article will show you how to use socialite.js to load in the common social networks that are built-in and how to load a pre-existing extension to expand the network support.

  • the problem with 3rd party scripts

    It has been well-documented that loading third-party scripts from sites like twitter and facebook can dramatically impact the performance of your site or even, at times, outright prevent your page from fully rendering for the user. there was even a good talk about this topic by steve souders at fluent 2012 and a good article by joshua bixby recently.

    essentially what can happen is that, assuming you attempt to load the third party script before the body of your page renders and that scripts host is either slow to respond or completely unresponsive, this could impact your pages performance. of course, the last thing you want is for your page to become unresponsive simple due to a silly facebook like button on your blog during a day facebook is down.s

    integrating socialite.js

    one potential solution to this issue is to use asynchronous loading of third party scripts and this is exactly what socialite.js by david bushell is designed to help you do very simply. essentially, socialite.js is a mi-cro-framework designed specifically for asynchronously loading and rendering third-party social sharing scripts. It comes with support for pretty much all of the most popular social networks and, while it also comes with a number of pre-built extensions, it is designed to be extended should you require additional networks.

    lets look at a quick example which I have implemented on my blog. previously, I had social sharing but-tons for twitter, facebook and google plus all manually added via the instructions for each on their re-spective sites. while many social networks have been improving their implementations, this still usually requires adding a script to load either in my document head or body as well as potentially some addi-tional javascript code to customize and render the button.

    In order to replace this, first I need to load the socialite.js script. Ive downloaded the minified version and imported it into my site immediately prior to my end tag. I should note at this point that socialite.js does depend upon jQuery so you will also need to have loaded that prior.

    Next I need to initialize socialite.js when my document loads.

    $(document).ready(function() { Socialite.load($(#social)); });

    this is pretty much the most basic implementation available with socialite.js. It does allow a good deal of settings and other customizations should you require them but for a basic share button from the most common networks this may not be necessary (and wasnt for me). one of the useful features of socialite, which I dont cover here, is that you can load these buttons on events other than document ready, includ-ing on mouse events like hover, for example.

    you will notice though that I am passing in a jQuery object for the doM element with the Id of social. for socialite, this is the context within which it will search for elements to replace with the proper sharing buttons. you will want to limit the context to prevent socialite from having to search too much of your page, nevermind the entire document.

    so lets take a look at my social doM element to see how to implement twitter.

    2/4

  • Share son Twitter

    In my case as in the examples provided, the doM element is a unordered list that is styled to hide the bullets and text within the links. essentially, this is just a container for socialite to fill, but the link also provides quite a bit of data and properties that I want to pass to twitter. the way socialite works, these properties will generally be identical to the properties youd have used on your script. so, in this case my twitter link without socialite would have been identical apart from the class (and would have had some additional javascript beneath the link as you can see in the instructions on twitters site). socialite does require the data- prefix on properties but this appears to also be a standard convention of many, though not all, social sharing scripts. while this means that youll have to reference the documentation for each share button separately and the properties wont necessarily match between twitter and, say, facebook, it also makes it extremely easy to convert existing buttons to use socialite.

    heres how I added google plus...

    Share on Google+

    ...and facebook...

    Share on Facebook

    ...and finally linkedIn.

    Share on LinkedIn

    support for all of these social networks are built-in by default into the standard socialite.js script. how-ever, there are obviously plenty of other social networks you may wish to support that are, thankfully, sup-ported via pre-built extensions. lets discuss using those.

    adding plugins for additional networks

    as weve seen, adding the default extensions is quite easy, but what if you wanted to support others such as pinterest or spotify? these and many others are already provided for you as extensions to socialite. heres a list of currently provided extensions:

    3/4

  • ABOUT THIS ARTICLE

    brian rinaldi is a Content and Community Manager 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.com and is an unreformed twitter addict. http://remotesynthesis.com/

    @remotesynth

    Socialite.jshttp://socialitejs.com/

    Twitter buttonshttps://twitter.com/about/resources/buttons#tweet

    Web Performance Todayhttp://www.webperformancetoday.com/2012/05/16/control-third-party-web-site-content/

    ONLINE RESOURCES

    buffer

    github

    hacker News

    pinterest

    spotify

    vk.com

    I decided to add in the hacker News button just for kicks (Ive never managed many links or votes on hN but maybe this will help after all). the first thing I did was obviously download and import the extension (you may, in the long run, want to combine extensions into the minified socialite.js to reduce http re-quests):

    Now, one thing to be aware of with socialite extensions is that it isnt always obvious what, if any, prop-erties you need to provide, even after looking into the extension code. however, I initially just included another list item to be replaced for hacker News like this:

    Share on Hacker News

    this didnt work but looking into my htMl via Chrome developer tools, I was able to discern that the url it was using for the generated ifame was http://hnbutton.appspot.com/button which, if you open it, will show that a title and url properties are required. knowing that we must use the data- prefix for socialite, the correct code to include this button would be:

    Share on Hacker News

    once you know what the necessary or available properties are, its really easy.

    going forward

    My goal is to follow up this article with one covering how to build your own socialite extensions for addi-tional social networks. while this isnt well documented at the moment, david has been very responsive and I hope to contribute to the project both by creating an extension for this tutorial as well as document-ing how to create one.

  • appliness( DONT WORRy, BE APPLI

    by jeremy khan

    Playground

    - Javascript

    - Uglify

    - C++

    Difficulty- rookie- intermediate

    - expert

    Todo list- optimize- be old- readable

    TREATING jAVASCRIPT LIkE A 30 yEAR OLD LANGuAGEjereMy khaN works for youtube, loves opeN sourCe, aNd wrItes lots of javasCrIpt... but he doesNt lIke thIs laNguage. dIsCover why aNd how he haNdles It.

    introduction

    I dont like javascript. I write an enormous amount of javascript in fact I write it almost exclusively but I dont really like it as a language. I dont want to write a giant screed as to why I dont like the lan-guage, but suffice it to say that it lacks some really basic features (like default parameters), and its lack of clearly defined rules (semicolons, whitespace) create lots of headaches.

    something that has helped me keep javascript manageable and even fun is the coding styles I have developed. I create a lot of rules for myself that result in extremely readable and descriptive code. this equates to lots of boring style constructs and boilerplate comments that add absolutely no features to what Im writing, but go a long way to keep the code obvious and explicit. I write javascript as though it were C, at least to some extent. why do I create this extra work for myself? because reading code sucks. It will always suck, whether you are reading your own code or somebody elses. especially when it comes to my open source projects, I really, really want people to read and contribute to the code I write. It is absolutely worth it to take extra time to trivially polish code so that fellow humans can easily dive right in. additionally, I read my code many more times than I write it, so I want to have mercy on my future self by writing painfully obvious and straight-forward code.

  • Much of my style is rooted in the google javascript style guide. this is largely due to the fact that I need to follow this style guide in my day job. however, I have fallen in love with the strictness of the google way, and have adapted it for my own open source projects. for said open source projects, I dont follow google 100% because, well, I have my own opinions on clean code. Its needless to go over every minu-tiae of my style, but I think there a few basic rules that go a long way in keeping large amounts of code sane and manageable.

    80 character line limits

    theres nothing more irritating when trying to grok code than scrolling around to see the entire line. Its a mental context killer. while any text editor worth its disk space has the option to wrap text automatically, chances are your code will be read in an environment that doesnt. this includes ClI programs (like diff and less) and web-based source viewers like github. dont make people scroll, its mean.

    at some point in computer history, somebody created an 80 character line limit for code. Its formally documented in the python style guide, and I think its totally awesome. this has two benefits. first, as I mentioned, you eliminate the need to horizontally scroll. More substantively, this promotes code simplic-ity. when you restrict yourself to 80 characters before a line break, youre more likely to break statements up into smaller chunks. I dont like clever code that crams a bunch of nested function calls into lines like this:

    //ONE LINE OF CODEsetTransformStyles(context, buildTransformValue(this._transformOrder,_.pick(state, transformFunctionNames)));

    this is painful to read. theres so much to parse mentally, and I might even have to scroll. Id much rather read each meaningful chunk line by line, and then see how it all comes together:

    // Formatted version of the above snippet. Taken from the Rekapi source.var transformProperties = _.pick(state, transformFunctionNames);var builtStyle = buildTransformValue(this._transformOrder, transformProperties);

    setTransformStyles(context, builtStyle);

    while I can add line breaks to the original one-liner to make it conform to the 80 character limit, the limit annoys me into breaking things up into shorter, more obvious statements. I want to be annoyed into this, it makes my code more readable in the long run.

    2/6

  • strict-ish typing with annotations

    the google Closure Compiler has a lot of rules regarding code annotations. these are necessary to al-low the compiler to perform the advanced compile-time optimizations, and it blows up when there is a type error. the annotations serve to clearly communicate to the compiler what the expected inputs and outputs of every function are.

    It turns out that taking the time to explicitly declare the input and output types of a function to communi-cate to the compiler have a nice side effect: the types are also explicitly communicated to humans! lets take an example of some magical code:

    function addNumbers (number1, number2) { return number1 + number2;}

    simple enough, but what if we do this:

    var sum = addNumbers(5, 10);console.log(sum); // -> 510

    whoops. If the client of this code assumes that addNumbers will do any typecasting for them, they will get unexpected results. however, if we explicitly annotate the function, we leave very little open to in-terpretation:

    /** * @param {number} number1 * @param {number} number2 * @return {number} */function addNumbers (number1, number2) { return number1 + number2;}

    Much better. very clear, very explicit. we can even take this a step further and add some documentation for the poor soul who has to read this code in the future:

    /** * Adds two numbers. * @param {number} number1 * @param {number} number2 * @return {number} */function addNumbers (number1, number2) { return number1 + number2;}

    Now, you by no means have to get this detailed with every function that you write. If a function is simple and obvious enough, I often just annotate the types and omit the documentation text. just be pragmatic about it.

    3/6

  • the new keyword

    all of the cool kids seem to really hate the new javascript keyword. apparently its totally old school and not at all trendy, so therefore you shouldnt use it. dmitry baranovskiy seems to have a particular distaste for it (august 2011):

    well, I really like the new keyword. when I see new in code, I read it as make a new instance of the fol-lowing. heres an example of why I like this clarity:

    var kitty = Cat();

    this is simple enough, but kitty could be anything. Cat could be giving us a number, for all we know. I prefer this:

    var kitty = new Cat();

    you may prefer to just capitalize your constructors, but I feel that using new helps to clearly communicate that a function is actually a constructor.

    I tweeted recently about new operator: if your JS library API expecting me to write new youre doing it wrong. Let me clarify it a bit.

    I am not saying that using new operator is a bad idea, its an essential operator, but asking me to use it with your API is a bad idea. Lets look at box2d.js API for example. Because it was supposed to copy C++ API, it took all C-like decisions and copied it straight to JavaScript. Its ok for something that was ported, but I see the same patterns in APIs created in JavaScript from the scratch.Example:

    var m_world = new b2World(new b2Vec2(0.0, -9.81), true);

    I would say it should look something like this instead:var m_world = box.world(0.0, -9.81);

    Why is it better? - Saves characters to type, makes code less verbose - If you put new by mistake nothing will happen - User shouldnt care if your function returns object literal or instance of some class

    I will illustrate last point on Raphal code. Lets say you want to create a circle and you want to take it bounding box and log x and width of it:var c = paper.circle(x, y, r), bb = c.getBBox(); console.log(bb.x, bb.width);

    With new approach I should write it like this:var c = new paper.Circle(x, y, r), bb = new BBox(c); // global? may be Raphael.BBox()? console.log(bb.x, bb.width);

    I found last one to be harder to read, error-causing and generically not nice.

    4/6

  • compile-time defines

    Compilers are totally awesome. generally speaking, you shouldnt deploy production code unless its been compiled with tools such as the google Closure Compiler or uglifyjs. for my open source projects, I prefer uglifyjs. I actually get better compression with Closure Compiler, but uglifyjs is easier to de-velop with. uglifyjs also has a few really awesome features. one that Ive fallen in love with is code pre-processing with compile-time defines. this feature is a throwback from the C world, and probably other compiled languages that are older than I. In any case, using defines lets you tailor your compiled binaries to fulfill various requirements. for example, you can use defines to tailor a build for mobile platforms that need different code than desktop platforms.

    Im using defines for rekapis testing hooks. there are some methods that I want to expose for my unit tests, but I dont want to expose them in the compiled code that gets sent to users. Its just wasted band-width and Cpu cycles to parse it. heres how I set it up:

    // At the beginning of the libraryif (typeof KAPI_DEBUG === undefined) { var KAPI_DEBUG = true;}

    // Later on in the codeif (KAPI_DEBUG) { Kapi._private = { calculateLoopPosition: calculateLoopPosition ,updateToCurrentMillisecond: updateToCurrentMillisecond ,tick: tick ,determineCurrentLoopIteration: determineCurrentLoopIteration ,calculateTimeSinceStart: calculateTimeSinceStart ,isAnimationComplete: isAnimationComplete ,updatePlayState: updatePlayState };}

    Kapi._private has references to a bunch of methods that will never be used publicly, but need to be exposed for testing. KAPI_DEBUG is a global variable (eeek!), but is only present in the source code, not the compiled binary. this is thanks to my build.js script:

    var uglifyJS = require(uglify-js);var jsp = uglifyJS.parser;var pro = uglifyJS.uglify;var ast = jsp.parse( _fs.readFileSync(_distFileName, utf-8) );

    ast = pro.ast_mangle(ast, { defines: { KAPI_DEBUG: [name, false] } });

    this tells uglifyjs to set KAPI_DEBUG to false when it is compiled. because my debugging code is wrapped in conditional that tests the boolean value of KAPI_DEBUG, it is marked as unreachable code and not included in the binary. perfect!

    5/6

  • ABOUT THIS ARTICLE

    hes a web developer in san francisco. he writes front end code for youtube and enjoys a nice Mo-cha. Check out his github and some of his work hes done in the past.

    http://jeremyckahn.github.com/

    @jeremyckahn

    His Dev Bloghttp://jeremyckahn.github.com/

    His gitHub accounthttps://github.com/jeremyckahn

    Rekapihttps://github.com/jeremyckahn/rekapi

    ONLINE RESOURCES

    something to note: at the time of this writing, this feature is poorly documented, but a pull request is pending.

    i code like an old man

    Ive been writing javascript for three-ish years at this point and have built up some strong stylistic pref-erences. Its worth noting that I started out with C++ before switching to dynamic languages. while my coding style may not be everyones cup of tea, it is optimized for readability. I think a lot of the newer coding conventions do not lend themselves to clarity and approachability. yes, I use semicolons, new, and love a nicely architected inheritance chain. I dont do these things out of obstinance, but practicality. I suggest that you adopt whatever coding style results in code that is readable to others.

    I write code that is boring, because boring code is readable code. I would contend that readability gener-ally has more impact on the success of a project than micro-optimizations and stylistic experimentation. If that means writing like a C coder in the 80s, then so be it.

  • appliness( DONT WORRy, BE APPLI

    by raymond Camden

    Playground

    - Storage

    - HTML

    - JavaScript

    Difficulty- rookie- intermediate

    - expert

    Todo list- pictures- art- save search

    LOCALSTORAGE ExAMPLE: STORING PREVIOuS SEARCHESIve Made It Clear that IM a huge faN of loCalstorage. whIle sIttINg IN the houstoN aIr-port for MaNy hours thIs week, I deCIded to whIp up a lIttle exaMple that deMoNstrates oNe of the praCtICal uses for thIs feature.

    building templates

    I built a simple ajax-based search page and then added localstorage as a way to remember your previous searches. this isnt anything spe-cial, but I think its another good example of the feature. lets begin by taking a look at the application before any use of localstorage.

  • the application makes use of bootstrap, jQuery, and handlebars, but for now, lets just focus on the ja-vascript and the template:

    $(document).ready(function() {

    var source = $(#artResultsTemplate).html(); var template = Handlebars.compile(source);

    $(#searchButton).on(click, function(e) { e.preventDefault(); var search = $.trim($(#search).val()); if(search === ) return; console.log(search for +search); $.get(service.cfc?method=searchArt, {term:search}, function(res,code) {

    var html = template({results:res}); $(#results).html(html); },JSON);

    }); });

    Results {{#if results}} {{#each results}} {{name}} {{description}} Created by {{artist}} and selling for ${{price}} {{/each}} {{else}} Sorry, no results. {{/if}}

    you can see that I begin by compiling my handlebars template (this is used for the results), and then I define my click handler for the search button. all the handler does is grab the search string, pass it to a Coldfusion service that hits the database, and then passes the results to my handlebars template.

    2/4

  • beautiful - and the code is rather simple. you can test this yourself. Id recommend searching for oil, moon, paint, and beer:

    ok, now lets talk about the next version. the updated version will use localstorage to remember your last five searches. I decided on five mostly because it just felt right. I thought ten might be a bit much.

    to store the last five values, Ill use an array. you cant store complex variables in localstorage, but you can easily serialize them with jsoN. so for example:

    var pastSearches = [];

    if(localStorage[pastSearches]) { pastSearches = JSON.parse(localStorage[pastSearches]);}

    that isnt too complex, is it? storing the value isnt too hard either. I do a check to see if the value exists in the array, and if not, put it in the front and pop one off the end if the array is too big.

    if(pastSearches.indexOf(search) == -1) { pastSearches.unshift(search); if(pastSearches.length > 5) { pastSearches.pop(); } localStorage[pastSearches] = JSON.stringify(pastSearches);}

    3/4

  • all thats left then is to simply write out the past searches and listen for click events on them.

    function drawPastSearches() { if(pastSearches.length) { var html = pastSearchesTemplate({search:pastSearches}); $(#pastSearches).html(html); }}

    $(document).on(click, .pastSearchLink, function(e) { e.preventDefault(); var search = $(this).text(); doSearch(search);});

    and voila - I can now remember your last five searches and provide an easy way for you to quickly rerun them. the code samples above are only the most important bits. I encourage you to view source on the updated version for the complete example.

    get the source code

    the full source code of this htMl sample:

    https://github.com/michaelchaize/appliness/blob/master/ray-storage/index.html

    Coldfusion code (Query):

    https://gist.github.com/3106450

  • appliness( DONT WORRy, BE APPLI

    by andrew trice

    Playground

    - Edge

    - DOM

    - Mustache

    Difficulty- rookie- intermediate

    - expert

    Todo list- animate- extract- modules

    uSING EDGE ANIMATIONS AS COMPONENTSaNdy deMoNstrates how to use adobe edge to Create aNIMated CoMpoNeNts IN your ap-plICatIoNs.

    edge animations

    youve probably heard of adobe edge, a timeline-based tool for creating interactive and animated htMl content. edge enables you to easily create interactive experi-ences that rely only on htMl, Css, and javascript. If youve used oth-er adobe Creative suite tools, such as flash professional, premiere, or after effects, then edge will prob-ably look quite familiar. you have a timeline and controls to edit your content. edge has been used to ani-mated the cover of the july issue of appliness with eric Meyer.

  • Currently, the normal use case for edge is creating interactive experiences that are loaded when the page loads. you can chain animation compositions in sequence, but they have to be in the same wrapper htMl file. this works great for a number of use cases, but one thing I wanted to do is create an edge animation and use that as a component that is arbitrarily added to the htMl doM at any point in time. My findings: It can be done, although with a few gotchas.

    using edge animations as components inside of a larger htMl experience isnt the primary use case which edge was designed for. however this use case is being evaluated and may end up in edge at a later date. If that happens, this process will become much easier.

    If youre wondering what was I thinking?, Ill try to explain while discussing the process of building htMl-based apps, I had the thought:

    Wouldnt it be cool to have a really elaborate loading animation while loading data from the server? We could use Edge to build the animation!

    as a proof of concept, I created a very basic application that loads two separate edge animations on demand. before I go into too much detail on what I built, lets take a look at the running example. this example has two buttons, one shows a car animation, one shows an airplane animation. Its pretty basic and straightforward:

    the first thing that I did was create two simple edge animations which you can view in this sample: cars and planes. all images used in these animations were obtained from thenounproject.com.

    playing with mustache

    once the animations were complete, I started looking at the generated htMl output, and figuring out how I can add it to the htMl doM of an existing htMl page. I then started putting together the sample application using Mustache.js as a templating engine to abstract htMl views away from application log-ic. Note: I also have a simple utility that enables me to include Mustache.js templates in separate htMl 2/5

  • files, so that I can keep everything separate.

    first, I created the basic shell for the application. It is more or less an empty htMl structure, where all content is added a