<?xml version="1.0" encoding="UTF-8"?> <rss
version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
xmlns:series="http://organizeseries.com/"
> <channel><title>SitePoint &#187; Tools and Libraries</title> <atom:link href="http://www.sitepoint.com/category/javascript/toolsandlibraries/feed/" rel="self" type="application/rss+xml" /><link>http://www.sitepoint.com</link> <description>Learn CSS &#124; HTML5 &#124; JavaScript &#124; Wordpress &#124; Tutorials-Web Development &#124; Reference &#124; Books and More</description> <lastBuildDate>Mon, 13 May 2013 13:12:07 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.5.1</generator> <item><title>Unheap.com: a Better jQuery Plugin Repository?</title><link>http://www.sitepoint.com/unheap-jquery-plugin-repository/</link> <comments>http://www.sitepoint.com/unheap-jquery-plugin-repository/#comments</comments> <pubDate>Fri, 03 May 2013 16:36:48 +0000</pubDate> <dc:creator>Craig Buckler</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[Open source]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[HTML5 Dev Center]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[plugins]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=65656</guid> <description><![CDATA[Do you need a jQuery plugin? Are you finding it difficult to locate one on the official repository? Craig suggests Unheap.com may be a better alternative...]]></description> <content:encoded><![CDATA[<p></p><p>I&#8217;ve never been <a
href="http://www.sitepoint.com/jquery-plugins-registry/">particularly complimentary</a> about the <a
href="http://plugins.jquery.com/">official jQuery Plugin Registry</a>. The team are working on it, but perhaps the kindest observation is that it&#8217;s <em>&#8220;ctional&#8221;</em> &#8212; functional with all the &#8220;fun&#8221; removed. The system lacks an easy interface, good search facilities, online demonstrations, developer ratings and reviews.</p><p>As an alternative, why not try <a
href="http://www.unheap.com/"><strong>unheap.com</strong></a> &#8212; a new independent jQuery plugin repository&hellip;</p><p><a
href="http://www.unheap.com/"><img
src="http://blogs.sitepointstatic.com/images/tech/821-unheap-jquery-plugins.jpg" alt="Unheap.com" class="center" /></a></p><p>The benefits of <a
href="http://www.unheap.com/"><strong>unheap.com</strong></a> become apparent the moment you use it:</p><ul><li>The site has a gorgeous dynamic and responsive interface &#8212; it&#8217;s a pleasure to use</li><li>Plugins are categorized in sections and sub-sections for interface, inputs, media, navigation and miscellaneous code.</li><li>The search facility works well.</li><li>Plugin lists have direct links to demonstration pages and videos.</li><li>Related plugins are listed.</li><li>User views, votes and bug reports are recorded.</li><li>Social media sharing facilities are provided.</li><li>An RSS feed of new and updated plugins is available for you to check in <a
href="http://www.sitepoint.com/goodbye-google-reader/"><s>Google Reader</s></a>, erm, a compatible RSS Reader.</li><li>The <a
href="http://www.unheap.com/submit">plugin submission process</a> is easy and straight-forward.</li><li>Almost 700 plugins are available at the time of writing.</li></ul><p>I&#8217;m impressed. Unless the jQuery team can produce a system as nice as <a
href="http://www.unheap.com/">unheap.com</a>, perhaps they should give up now and adopt it as the &#8220;official&#8221; repository?</p><p>Unless you&#8217;ve found something better?&hellip;</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/unheap-jquery-plugin-repository/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Selective Content Loading</title><link>http://www.sitepoint.com/selective-content-loading/</link> <comments>http://www.sitepoint.com/selective-content-loading/#comments</comments> <pubDate>Wed, 03 Apr 2013 13:32:22 +0000</pubDate> <dc:creator>Andrew Fisher</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[Programming]]></category> <category><![CDATA[Responsive Web Design]]></category> <category><![CDATA[Tools and Libraries]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/?p=65082</guid> <description><![CDATA[Andrew Fisher, co-author of <em>Jump Start Responsive Web Design</em>, expands on the technique called selective content loading, referred to in the book.]]></description> <content:encoded><![CDATA[<p></p><p>One of the techniques we talk about in <a
href="http://www.sitepoint.com/books/responsive1/">Jump Start Responsive Web Design</a> is called Selective Content Loading (SCL). This technique is really useful in situations where you want to load small pieces of data into an already loaded page in a structured way. When would this be useful?</p><ul><li> When you have serious bandwidth issues between your server and the end user’s device (for example, on a mobile connection that is moving on a poor network with lots of errors and having to deal with cell handoff).</li><li> When your pages are largely the same structurally from page to page and simply reloading the content saves many requests.</li><li> If you have chunked your content nicely and want to simply load in the next piece in the sequence (for example, infinite scrolling on a Twitter feed)</li></ul><p>Some of these issues can be dealt with by good caching and using local storage and these should definitely be explored as good practices generally. However, even with smart asset caching you still require server round trips to retrieve a document, all the page HTML still has to be sent to the browser and then the browser still has to render the page.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><p>If your page has only added a couple of additional bits of data (for example, a tweet) or is only changing a small amount of content (for example, the details for a product) then SCL may be a good option for you. This doesn’t work in every circumstance and it also causes a number of possible issues with URLs, browser history and what content gets spidered on a “page” by search engines (if this important to you).</p><p>Recapping our approach from Jump Start RWD, this is what we’re going to do conceptually:</p><ul><li> On the first page request we’ll load up all of the page content including the site navigation, content layout, CSS and JS files as normal.</li><li> After the page has loaded we’ll override all of the links in our page to make them XHRs rather than a standard request for a document.</li><li> We’ll then process the response (the XHR response will only be the internal page content in JSON rather than the entire page) and overwrite the content that was in the page.</li><li> We can then use <code>pushState()</code> to modify our browser history (so the URL updates to something shareable and we can go backwards if needs be).</li></ul><p>Here’s an example that should illustrate the point simply. The content has been truncated purposefully in order to keep this concise.</p><p>We’re going to set up a page that can load content about books without having to reload the entire page, just the pertinent content. We’ll also use <code>pushState()</code> from the History API to ensure that if the user wants to share or come back to the URL they&#8217;ll be able to do so.</p><p>To make things simple to express, we’re going to use jQuery for the DOM manipulation and a JavaScript templating library called <a
href="http://handlebarsjs.com/">Handlebars.js</a>. If you haven’t checked out JavaScript templating options and what they can do, Handlebars is an excellent choice to get your feet wet.</p><p>The core of our solution relies on the fact that URLs can respond differently depending on whether they are an XHR or a normal HTTP request. If the server gets a normal request then the view will deliver the full HTTP response (containing all the document and then the JS, CSS etc). If the server gets an XHR, it will respond with JSON which only contains data about the book requested.</p><p>So, as an example, the standard HTTP response for the “Frankenstein” page looks like this:</p><pre>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;script type="text/javascript" src="<a href="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js</a>"&gt;&lt;/script&gt;
&nbsp;
var original = null;
var backtostart = true;
&nbsp;
  &lt;script type="text/javascript"&gt;
      ($(document).ready(function() {
          var source = $("#story-template").html();
          var template = Handlebars.compile(source);
&nbsp;
          var story_link_handler = (function(evt) {
              evt.preventDefault();
              $.get(this.href, function(data) {
                  $("#contentarea").html("");
                  $("#contentarea").html(template(data));
                  history.pushState({url:data.location}, data.title, data.location);
              }, "json");
          });
&nbsp;
          $("ul#storylist li a").bind("click", story_link_handler);
&nbsp;
          $(window).bind("popstate", function(evt) {
              if (event.state) {
                  url = event.state.url;
                  $.get(url, function(data) {
                      $("#contentarea").html("");
                      $("#contentarea").html(template(data));
                  }, "json");
               backtostart = false;
              } else {
               if (! backtostart) {
                  backtostart = true;
                      $("#contentarea").html("");
                      $("#contentarea").html(original);
               } else {
                 original = $("#contentarea").html();
                    backtostart = false;
               }
            }
          });
&nbsp;
      }));
  &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;ul id="storylist"&gt;
      &lt;li&gt;&lt;a href="mobydick"&gt;Moby Dick&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href="gulliverstravels"&gt;Gulliver's Travels&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href="frankenstein"&gt;Frankenstein&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;div id="contentarea"&gt;
      &lt;article id="story"&gt;
          &lt;h1&gt;Frankenstein&lt;/h1&gt;
              &lt;h2&gt;Mary Shelley&lt;/h2&gt;
              &lt;p&gt;Doctor creates artificial life&lt;/p&gt;
          &lt;/article&gt;
      &lt;/div&gt;
&lt;script type="text/javascript" src="handlebars.js"&gt;&lt;/script&gt;
      &lt;script id="story-template" type="text/x-handlebars-template"&gt;
      &lt;article&gt;
          &lt;h1&gt;{{title}}&lt;/h1&gt;
          &lt;h2&gt;{{author}}&lt;/h2&gt;
          &lt;p&gt;{{synopsis}}&lt;/p&gt;
      &lt;/article&gt;
      &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre><p><em>NB you can download code used in this article in a zip file linked at the end of this article</em></p><p>However, the equivalent JSON response for an XHR will look like this instead:</p><pre>{
  "location": "/frankenstein",
  "title": "Frankenstein",
  "author": "Mary Shelley",
  "synopsis": "Mad doctor creates artificial life"
}</pre><p>All the code required to make the selective loading work is requested and loaded in the first request. After that, we only get the data and then load it into the template. Let’s take a look at how the code works.</p><pre>  &lt;script id="story-template" type="text/x-handlebars-template"&gt;
      &lt;article&gt;
          &lt;h1&gt;{{title}}&lt;/h1&gt;
          &lt;h2&gt;{{author}}&lt;/h2&gt;
          &lt;p&gt;{{synopsis}}&lt;/p&gt;
      &lt;/article&gt;
  &lt;/script&gt;</pre><p><em>NB you can download code used in this article in a zip file linked at the end of this article</em></p><p>Handlebars uses a script element to create a template for what an article looks like (this content won’t be rendered by the browser as it won’t take an action on its type). Variable locations are defined using <code>{{variable}}</code> syntax. You can do a lot more with Handlebars (conditionals, loops, block execution etc) that we aren’t using in this instance though. Note the ID for the script, we need this so we can pass it into the Handlebars template compiler.</p><p>In our document ready function, we grab the HTML from the template script tag we defined above and then we compile it into a template object we can use with new data later.</p><pre>  var source = $("#story-template").html();
  var template = Handlebars.compile(source);</pre><p>Next, we define a function we can use for our link <code>onclick</code> event handler. Here we’re simply stopping the actual request to the file by preventing its default behaviour. From there we make a jQuery XHR that returns JSON to the URL that was defined in the link’s <code>HREF</code> attribute.</p><pre>  var story_link_handler = (function(evt) {
      evt.preventDefault();
      $.get(this.href, function(data) {
          $("#contentarea").html("");
          $("#contentarea").html(template(data));
          history.pushState({url:data.location}, data.title, data.location);
      }, "json");
  });</pre><p>When the response comes back, we simply overwrite the <code>div</code> content area that holds all our book data.</p><pre>$("#contentarea").html(template(data));</pre><p>We also use <code>pushState()</code> to push the URL we just requested onto the browser history so we can go backwards using the back button.</p><pre>history.pushState({url:data.location}, data.title, data.location);</pre><p>That’s not quite the whole picture with <code>pushState()</code>, though, in order for it to “just work” for the user. We next create a <code>popstate</code> event handler on the window so that when the user hits the back button we can update the content with the appropriate data for the book. In this case we’re going and getting the data again using an XHR. With pushstate, it’s possible to store data in a <code>state</code> object. In our case the amount of data is small and it’s bad practice to load up the user’s browser with additional data (especially on mobile) so only do it if you can guarantee it’s a tiny amount.</p><pre>  $(window).bind("popstate", function(evt) {
      if (event.state) {
          url = event.state.url;
          $.get(url, function(data) {
              $("#contentarea").html("");
              $("#contentarea").html(template(data));
          }, "json");
      }
  });</pre><p>One of the things we need to consider with this technique is what happens when the browser gets back to the start of the list. That is, you’ve popped all of your XHRs off the stack and you’re back to where you started.</p><p>To remedy this, we use a flag to determine if we’re back to the start or not and we save the content that was in <code>#contentarea</code> so we can replace it. You can use other techniques such as simply hiding the original content area or storing the original document’s JSON.</p><p>We then update the <code>popstate</code> event to check if there’s no <code>event.state</code>. If so, we revert to our original form.</p><pre>$(window).bind("popstate", function(evt) {
              if (event.state) {
                  url = event.state.url;
                  $.get(url, function(data) {
                      $("#contentarea").html("");
                      $("#contentarea").html(template(data));
                  }, "json");
               backtostart = false;
              } else {
               if (! backtostart) {
                  // revert the content to the original
                  backtostart = true;
                      $("#contentarea").html("");
                      $("#contentarea").html(original);
               } else {
                 // store original content to retrieve later
                 original = $("#contentarea").html();
                    backtostart = false;
               }
            }
          });</pre><p>Finally, we add our <code>click</code> event handler to all the relevant links. In our instance, we’re just using the links in the list, but in practice you could do this to a whole range of links based on <code>class</code> or <code>HREF</code> attributes.</p><pre>$("ul#storylist li a").bind("click", story_link_handler);</pre><p>The rest of the page is the page structure and the actual content that was requested &#8211; in this case the <code>/frankenstein</code> URL.</p><p>As can be seen, this approach gives us a nice, responsive setup. The initial page request is a little heavier (in this case about 1Kb) but provides all of the scaffolding needed to layout the page and provide the interactions. Subsequent requests get the benefit of only having to return very small snippets of data, which are then loaded into the template.</p><p>The URL is updated using <code>pushState()</code> which means the user can still share the URL using intents or copy and paste and that URL will work properly for whomever it is shared with. You also get the benefit that each document still exists properly &#8211; this means search engines can still correctly index your site, if that’s needed.</p><p>One of the things we need to be careful of with this technique is that if we have content that exists in many different templates, the benefits from only loading the snippets of data via XHR will be destroyed by having to load all of the different content templates into the first page request and masking it from the user until it&#8217;s used. Don’t forget, all of the HTML still has to be loaded, regardless of whether it’s used or not.</p><p>Where this technique works particularly well is in an “infinite scroll” scenario such as a stream of content or very long article. The content type doesn’t change almost at all (or only within a very defined way)—this technique does for “page content” as a whole what the lazy loading technique does for images within a page. If you’ve taken the time to chunk your content, this can be especially effective as it means you can avoid the user hitting “goto page 2” even though search engines will follow happily.</p><p><a
href="http://blogs.sitepointstatic.com/examples/selective-content-loading/scl_files.zip">Download code files used in this article</a></p><p><em>Delve further into the world of responsive web design in Andrew&#8217;s new book with Craig Sharkie: <a
href="http://www.sitepoint.com/books/responsive1/">Jump Start Responsive Web Design</a>.</em></p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/selective-content-loading/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Unit Testing Backbone.js Applications</title><link>http://www.sitepoint.com/unit-testing-backbone-js-applications/</link> <comments>http://www.sitepoint.com/unit-testing-backbone-js-applications/#comments</comments> <pubDate>Mon, 25 Feb 2013 09:00:01 +0000</pubDate> <dc:creator>Stephen Thomas</dc:creator> <category><![CDATA[Advanced]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[Backbone.js]]></category> <category><![CDATA[testing]]></category> <category><![CDATA[Unit Tests]]></category> <guid
isPermaLink="false">http://jspro.com/?p=2136</guid> <description><![CDATA[After spending hours, maybe days, putting the finishing touches on an awesome new feature for your web application, you&#8217;re finally ready to see it in action. You add the new code to your JavaScript base, build the release candidate, and fire up your browser, expecting to be amazed. Then &#8230; Uh Oh&#8230; the new feature [...]]]></description> <content:encoded><![CDATA[<p></p><p>After spending hours, maybe <em>days</em>, putting the finishing touches on an awesome new feature for your web application, you&#8217;re finally ready to see it in action. You add the new code to your JavaScript base, build the release candidate, and fire up your browser, expecting to be amazed. Then &#8230; Uh Oh&#8230; the new feature may be working fine, but some other critical part of your app &#8211; a part you didn&#8217;t <em>touch</em> while developing the new version &#8211; has gone horribly awry. Now you&#8217;re faced with the challenge of backtracking through days of work to try and figure out how you broke the existing code. Happy days are definitely not here again.</p><p><span
id="more-63981"></span></p><p>That very scenario has bitten me more than I&#8217;d like to admit. And if you&#8217;ve been coding awhile, you&#8217;ve probably seen it as well. Consider, though, what makes this scenario so painful. It isn&#8217;t really because our new code broke existing code; that&#8217;s inevitable in development. The real pain is that it took so long to notice the breakage. With so much development since we knew our application was working, there&#8217;s a vast amount of code in which the bug may be hiding. And, though it may seem a bit like hunting for a needle in a haystack, we have no choice but to dive it.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><p>In this article we are truly going to banish this scenario from our JavaScript development. No more digging through hours, days, or weeks of code looking for a needle. The principle we&#8217;ll adopt is a simple one: find any bug <em>as soon as</em> we create it. That&#8217;s right; we&#8217;re going to set up a development environment and process that tells us immediately when we write code that introduces a bug. Furthermore, the extra effort we put into the process won&#8217;t go to waste once initial development is complete. The same test code that catches our development bugs will be completely reusable in an integration environment. We can easily incorporate the tests into our source code managements system, blocking bugs before they can even get into our code base.</p><p>In the four sections that follow, we&#8217;ll first look at the tools we need for a JavaScript testing environment. We&#8217;ll then consider a trivial application, one that&#8217;s simple enough to understand, yet has all the features and functionality that might exist in a real production web application. The final two sections demonstrate how we can use our environment to test the example app during development and, once initial development is complete, during integration.</p><h2>Assembling a JavaScript Testing Environment</h2><p>Our unit testing nirvana requires some development tools that may not be in your workbench (yet). The news, both good and bad, is that there are options aplenty. That&#8217;s good news because it gives us options, and that&#8217;s bad news because the pace of front end development today means that there are far too many options. To focus our evaluation, let&#8217;s be explicit about our top two goals. Everything else is secondary:</p><ol><li>Our environment must support frictionless, continuous testing during development.</li><li>Tests created during development must be equally usable in integration.</li></ol><h3>Execution Environments</h3><p>For JavaScript coding, there is no better development environment than the modern web browser. Whether your taste is Firebug or Webkit&#8217;s Developer Tools, the browser supports live DOM inspection and editing, full interactive debugging, and sophisticated performance analysis. Web browsers are great for development, and so our test tools and environment must integrate with in-browser development. Web browsers, however, are not so great for integration testing. Integration testing often takes places on servers somewhere in the cloud (or a least somewhere in the data center). Those systems don&#8217;t even have a graphical user interface, much less a modern web browser. For efficient integration testing, we need simple command line scripts and a JavaScript execution environment that supports them. For those requirements, the tool of choice is <a
href="http://nodejs.org">node.js</a>. Although there are other command line JavaScript environments, none has the breadth and depth of support to match node.js. In the integration phase, our test tools must integrate with node.js.</p><h3>Test Framework</h3><p>Now that we&#8217;ve established that our test tools must support both web browser and node.js environments, we can narrow the choices enough to select a core test framework. Many JavaScript test frameworks exist, but most are heavily biased towards browser testing; getting them working with node.js is usually possible, but often requires inelegant hacks or tweaks. One framework that does not suffer from this problem is <a
href="http://visionmedia.github.com/mocha/">Mocha</a>, which justifiably describes itself as:</p><blockquote><p>Mocha is a feature-rich JavaScript test framework running on node and the browser, making asynchronous testing simple and fun.</p></blockquote><p>Originally developed for node.js, Mocha has been extended to readily support web browsers as well. By using Mocha as our test framework, we can write tests that support both development and integration without modification.</p><h3>Assertion Library</h3><p>Unlike some JavaScript test frameworks, Mocha was designed for maximum flexibility. As a consequence, we&#8217;ll have to choose a few additional pieces to make it complete. In particular, we need a JavaScript assertion library. For that, we&#8217;ll rely on the <a
href="http://chaijs.com">Chai Assertion Library</a>. Chai is somewhat unique in that it supports all of the common assertion styles &#8211; <em>assert</em>, <em>expect,</em> and <em>should.</em> Assertion styles determine how we write tests in our test code. Under the covers, they&#8217;re all equivalent; it&#8217;s easy to translate tests from one assertion style to the other. The main difference in assertion styles is their readability. The choice of assertion style depends mostly on which style you (or your team) find most readable, and which style produces the most understandable tests. To see the difference, consider developing a trivial test for the following code:</p><pre class="brush: jscript; title: ; notranslate">
var sum = 2 + 2;
</pre><p>A traditional, assert-style test could be written as:</p><pre class="brush: jscript; title: ; notranslate">
assert.equal(sum, 4, &quot;sum should equal 4&quot;);
</pre><p>That test gets the job done, but unless you&#8217;ve grown accustomed to old-school unit testing, it&#8217;s probably a little challenging to read and interpret. An alternative assertion style uses <code>expect</code>:</p><pre class="brush: jscript; title: ; notranslate">
expect(sum).to.equal(4);
</pre><p>Most developers find expect-style assertions easier to read and understand than assert-style tests. The third alternative, <code>should</code>, makes test assertions even more like natural language:</p><pre class="brush: jscript; title: ; notranslate">
sum.should.equal(4);
</pre><p>The Chai library supports all three assertion styles. In this article we&#8217;ll stick with <code>should</code>.</p><h3>Spies, Stubs, and Mocks</h3><p>Most web apps, including the trivial example we&#8217;ll consider in this article, rely on third party libraries and services. In many cases, testing our code will require observing &#8211; or even controlling &#8211; those libraries and services. The <a
href="http://sinonjs.org">Sinon.JS</a> library provides a lot of tools for testing those interactions. Such tools fall into three general classes:</p><ul><li><em><strong>Spy</strong></em>. Test code that observes calls to functions outside of the code under test. Spies do not interfere with the operation of those external functions; they merely record the invocation and return value.</li><li><em><strong>Stub</strong></em>. Test code that stands in for calls to functions outside of the code under test. The stub code doesn&#8217;t attempt to replicate the external function; it simply prevents unresolved errors when the code under test accesses the external function.</li><li><em><strong>Mock</strong></em>. Test code that mimics functions or services outside of the code under test. With mocks, test code can specify the return values from those functions or services so it can verify the code&#8217;s response.</li></ul><p>Along with the Sinon.JS library itself, we can augment the standard Chai assertion library with <a
href="https://github.com/domenic/sinon-chai">Sinon.JS Assertions for Chai</a>.</p><h3>A Unit Test Development Environment</h3><p>The final tool for our testing workbench is a development environment for unit testing. For our example we&#8217;ll use <a
href="https://github.com/airportyh/testem">Test&#8217;em</a>. Test&#8217;em is a collection of handy scripts to set up and run a continuous test environment. We could, if we chose to, write the scripts ourselves and manage the environment manually; however, Toby Ho (Test&#8217;em&#8217;s creator) has put together an awesome package that can save us the trouble.</p><h2>The Example Application</h2><p>To see our testing environment in action, let&#8217;s consider a simple application. Although pared to its bare essentials, this application includes all the functionality required for a real application. (Complete source code for the application is available on <a
href="https://github.com/jsprodotcom/source/blob/master/jsunittest.zip">GitHub</a>.)</p><p>[image src="http://jspro.com/files/2013/02/01-jstest-app.png"]</p><p>Users can see their list of todos, and they can click on a check box to toggle any todo&#8217;s status.</p><h3>The Todos Database</h3><p>Our application starts with a database table that holds the information for todos. Here&#8217;s the SQL that we could use to create that table.</p><pre><code>CREATE TABLE `todos` (
  `id`       int(11)      NOT NULL AUTO_INCREMENT COMMENT 'Primary key for the table.',
  `title`    varchar(256) NOT NULL DEFAULT ''     COMMENT 'The text for the todo item.',
  `complete` bit(1)       NOT NULL DEFAULT b'0'   COMMENT 'Boolean indicating whether or not the item is complete.',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='To Do items.'
</code></pre><p>And here&#8217;s how the table might look after we&#8217;ve put some test data in it.</p><table><thead><tr><th>id</th><th>title</th><th>complete</th></tr></thead><tbody><tr><td>1</td><td>A sample todo item in the database</td><td>0</td></tr><tr><td>2</td><td>Another sample todo item</td><td>1</td></tr><tr><td>3</td><td>Yet another sample todo item</td><td>0</td></tr></tbody></table><p>As the table shows, our todos only include a primary key (<code>id</code>), a title, and a status bit to indicate whether or not they are complete.</p><h3>A REST API</h3><p>Our web application needs access to this database, so we&#8217;ll provide a standard REST interface. The API follows Ruby conventions, but can be easily implemented by any server technology. In particular:</p><ul><li><code>GET api/todos</code> returns a JSON-encoded array of all rows in the database.</li><li><code>GET api/todos/NNN</code> returns the JSON representation of the todo with <code>id</code> equal to <code>NNN</code>.</li><li><code>POST api/todos</code> adds a new todo to the database using the JSON-encoded information in the request.</li><li><code>PUT api/todos/NNN</code> updates the todo with <code>id</code> equal to <code>NNN</code> using the JSON-encoded information in the request.</li><li><code>DELETE api/todos/NNN</code> deletes the todo with <code>id</code> equal to <code>NNN</code> from the database.</li></ul><p>If you&#8217;re not particularly fond of Ruby, the source code includes a complete PHP implementation of this API.</p><h3>JavaScript Libraries</h3><p>Our modest application is simple enough to implement in pure JavaScript without any libraries, but we have far bigger plans. We may be starting small, but eventually the app will feature amazing functionality and a delightful user interface. In preparation for that day, we&#8217;ll build on a framework that can support our ultimate killer app:</p><ul><li><a
href="http://jquery.com/">jQuery</a> for DOM manipulation, event handling, and server communications.</li><li><a
href="http://underscorejs.org/">Underscore.js</a> to enhance the core language with many indespensible utilities.</li><li><a
href="http://backbonejs.org/">Backbone.js</a> to define the structure of the application in terms of models and views.</li></ul><h3>An HTML Skeleton</h3><p>Now that we know the components that will comprise our application, we can define the HTML skeleton that will support it. There&#8217;s nothing fancy about it (yet), just a minimal HTML5 document, some JavaScript files, and a small bit of code to get things started.</p><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;title&gt;&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;List of Todos&lt;/h1&gt;
    &lt;script src=&quot;lib/jquery-1.9.0.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;lib/underscore-min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;lib/backbone-min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;src/app-todos.js&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
      $(function () {
        var todos = new todoApp.Todos();
        todos.fetch();
        var list = new todoApp.TodosList({collection: todos});
        $(&quot;body&quot;).append(list.el);
      })
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre><h2>Testing During Development</h2><p>Now that we&#8217;ve selected our tools and specified the application, it&#8217;s time to start development. Our first task is installing the tools.</p><h3>Installing the Tools</h3><p>Even though we&#8217;ll be developing in the browser, our test environment relies on node.js. The very first step, therefore, is installing node.js and the node package manager (npm). There are executable binaries for OS X, Windows, Linux, and SunOS on the <a
href="http://nodejs.org/download/">node.js web site</a>, as well as a source code for other operating systems. After running the installer, you can verify  both node.js and npm from the command line.</p><pre><code>bash-3.2$ node --version
v0.8.18
bash-3.2$ npm --version
1.2.2
bash-3.2$
</code></pre><p>Everything else we need is conveniently available as a node package. The node package manager can handle their installation, as well as any dependencies.</p><pre><code>bash-3.2$ npm install jquery jsdom underscore backbone mocha chai sinon sinon-chai testem -g
</code></pre><h3>Creating the Project Structure</h3><p>The source code for this example includes a complete project structure with the following 15 files:</p><pre><code>todos.html
testem.json
api/htaccess
api/todos.php
lib/backbone-min.js
lib/chai.js
lib/jquery-1.9.0.min.js
lib/sinon-1.5.2.js
lib/sinon-chai.js
lib/underscore-min.js
mysql/todos.sql
php-lib/dbconfig.inc.php
src/app-todos.js
test/app-todos-test.js
test/mocha.opts
</code></pre><p>Here is what each folder and file contains:</p><ul><li><code>todos.html</code>: The skeleton HTML file for our application, shown in full above.</li><li><code>testem.json</code>: The configuration file for Test&#8217;Em; we&#8217;ll look at this in detail shortly.</li><li><code>api/</code>: A folder for our REST API implementation.<ul><li><code>api/htaccess</code>: Sample configuration for the Apache web server that supports our REST API.</li><li><code>api/todos.php</code>: PHP code to implement the REST API.</li></ul></li><li><code>lib/</code>: A folder for JavaScript libraries used by the app itself and the test framework.<ul><li><code>lib/backbone-min.js</code>: Minified version of Backbone.js.</li><li><code>lib/chai.js</code>: Chai Assertion Library.</li><li><code>lib/jquery-1.9.0.min.js</code>: Minified version of jQuery.</li><li><code>lib/sinon-1.5.2.js</code>: Sinon.JS library.</li><li><code>lib/sinon-chai.js</code>: Sinon.JS Assertions for Chai.</li><li><code>lib/underscore-min.js</code>: Minified version of Underscore.js.</li></ul></li><li><code>mysql/</code>: A folder for MySQL code for the application.<ul><li><code>mysql/todos.sql</code>: MySQL commands to create the application database.</li></ul></li><li><code>php-lib/</code>: A folder for PHP libraries and configuration for the application&#8217;s REST API.<ul><li><code>php-lib/dbconfig.inc.php</code>: PHP database configuration for the REST API.</li></ul></li><li><code>src/</code>: A folder for our client-side application code.<ul><li><code>src/app-todos.js</code>: Our application.</li></ul></li><li><code>test/</code>: A folder for test code.<ul><li><code>test/app-todos-test.js</code>: Test code for our application.</li><li><code>test/mocha.opts</code>: Configuration options for mocha; we&#8217;ll look at this in the next section.</li></ul></li></ul><p>During development, we&#8217;re only interested in three of these files, <code>testem.json</code>, <code>src/app-todos.js</code>, and <code>test/app-todos-test.js</code>.</p><h3>Configuring Test&#8217;Em</h3><p>The last step before actual development is defining the Test&#8217;Em configuration. That configuration resides in the JSON-formatted <code>testem.json</code>, and it&#8217;s simple enough to create in any text editor. We simply specify that we&#8217;re using Mocha (Test&#8217;Em supports several frameworks), and we list the JavaScript files our application and our test code requires.</p><pre class="brush: jscript; title: ; notranslate">
{
  &quot;framework&quot;: &quot;mocha&quot;,
  &quot;src_files&quot;: [
    &quot;lib/jquery-1.9.0.min.js&quot;,
    &quot;lib/underscore-min.js&quot;,
    &quot;lib/backbone-min.js&quot;,
    &quot;src/*.js&quot;,
    &quot;lib/chai.js&quot;,
    &quot;lib/sinon-chai.js&quot;,
    &quot;lib/sinon-1.5.2.js&quot;,
    &quot;test/*.js&quot;
  ]
}
</pre><h3>Start Developing</h3><p>Finally, we&#8217;re ready to code. In a command shell, navigate to the root folder of our project and execute the command <code>testem</code>. The Test&#8217;Em scripts will run, clearing the terminal window and giving us a URL in the upper right. Copy and paste that URL into our browser of choice and we&#8217;re off.</p><p>[image src="http://jspro.com/files/2013/02/02-jstest-testem.png"]</p><p>As soon as we launch the web browser, it will automatically execute any tests that we&#8217;ve defined. Since we&#8217;re just beginning development, we won&#8217;t have any code, nor any test cases. The browser will kindly point that out to us.</p><p>[image src="http://jspro.com/files/2013/02/03-jstest-browser-none.png"]</p><p>The terminal window from which we launched Test&#8217;Em will also give us the status.</p><p>[image src="http://jspro.com/files/2013/02/04-jstest-console-none.png"]</p><h3>A First Test Case</h3><p>In the spirit of true Test-Driven Development, we&#8217;ll begin by writing our first test case in the <code>test/app-todos-test.js</code> file. Like any good web app, we want to minimize global name space pollution. To do that, we&#8217;ll rely on a single global variable, <code>todoApp</code>, to contain all of our code. Our first test case will make sure that the global name space variable exists.</p><pre class="brush: jscript; title: ; notranslate">
var should = chai.should();
describe(&quot;Application&quot;, function() {
  it(&quot;creates a global variable for the name space&quot;, function () {
    should.exist(todoApp);
  })
})
</pre><p>As you can see, we need one preliminary statement to tell Mocha that we&#8217;re using Chai assertions. Then we can begin writing tests. By convention JavaScript tests are organized into blocks (which can be nested into sub-blocks, and so on). Each block begins with a <code>describe()</code> function call to identify what part of the code we&#8217;re testing. In this case we&#8217;re testing the overall application, so that&#8217;s the first parameter to <code>describe()</code>.</p><p>Within a test block, we document each test case by what it tests. That&#8217;s the purpose of the <code>it()</code> function. The way to read any test case is to combine the <code>describe()</code> and <code>it()</code> strings into a single statement. Our first test case, therefore, is</p><blockquote><p>Application creates a global variable for the name space</p></blockquote><p>The test code itself is inside the <code>it()</code> block. Our test case is</p><pre class="brush: jscript; title: ; notranslate">
should.exist(todoApp);
</pre><p>Now we have a complete test case. As soon as we save the file, Test`Em automatically takes over. It notices that one of our files has changed, so it immediately reruns the tests. Not surprisingly (since we haven&#8217;t written any code for the application yet), our first test fails.</p><p>[image src="http://jspro.com/files/2013/02/05-jstest-browser-fail.png"]</p><p>The terminal window updates automatically as well.</p><p>[image src="http://jspro.com/files/2013/02/06-jstest-console-fail.png"]</p><p>To make the test pass, we must create the global name space variable. We shift to the <code>srcapp-todos.js</code> file and add the necessary code.</p><pre class="brush: jscript; title: ; notranslate">
if (typeof todoApp === &quot;undefined&quot;) todoApp = {};
</pre><p>As soon as we save the file, Test`Em once again springs into action. We immediately get updated results for our test cases.</p><p>[image src="http://jspro.com/files/2013/02/07-jstest-browser-pass.png"]</p><p>Step back for a moment and consider what&#8217;s happening! Every time we make a change, either to the test code or to our application, Test`Em immediately re-runs our entire test suite. All we have to do is keep Test&#8217;Em&#8217;s browser or terminal window visible in a corner of our screen, and we can see the health of our code in real time, <em>as we&#8217;re developing</em>. We&#8217;ll know as soon as we introduce a bug, even if the bug manifests itself in a part of the code different from where we&#8217;re working. No more digging back through hours, days, or weeks of new code to figure out when we introduced a bug.</p><h3>Testing the Model</h3><p>With our development environment now fully established, we can begin developing the application. Since our app shows a list of todos, it might be good to create a model for those todos. The model will need to keep track of both the title of the todo and it&#8217;s status. Let&#8217;s add a unit test that verifies we can create an todo with reasonable defaults.</p><pre class="brush: jscript; title: ; notranslate">
describe(&quot;Todo Model&quot;, function(){
  describe(&quot;Initialization&quot;, function() {
    beforeEach(function() {
      this.todo = new todoApp.Todo();
    })
    it(&quot;should default the status to 'pending'&quot;,function() {
      this.todo.get('complete').should.be.false;
    })
    it(&quot;should default the title to an empty string&quot;,function() {
      this.todo.get('title').should.equal(&quot;&quot;);
    })
  })
})
</pre><p>There are several aspects of these tests worth noting.</p><ul><li>We can nest test blocks within each other. One test block will contain all the unit tests for the todo model, and a sub-block of those tests focuses on initialization.</li><li>Within a test block, we can define functionality to execute before every test. That&#8217;s the purpose of the <code>beforeEach()</code> block. In the example above, we&#8217;re creating a new instance of a Todo before every test.</li><li>The Mocha framework automatically makes sure that the JavaScript context (i.e. the value of <code>this</code>) is consistent for all our test cases. That&#8217;s why we can define <code>this.todo</code> in one function (the <code>beforeEach()</code> parameter) and safely reference it in other functions (such as the <code>it()</code> parameters). Without Mocha working behind the scenes to provide this consistency, JavaScript would define different contexts for each function.</li></ul><p>Of course, since we haven&#8217;t written the model code yet, all our tests will fail. (And we&#8217;ll know that immediately.) But once we&#8217;ve added the code for our model, the tests pass and we&#8217;re on our way.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.Todo = Backbone.Model.extend({
  defaults: {
    title: &quot;&quot;,
    complete:  false
  }
})
</pre><h3>Using Stubs for Third Party Functionality</h3><p>Now that we have a simple model for todos, we can start to define its behavior. One thing our model should do is update the database whenever any of its properties change. In a unit test environment, however, we won&#8217;t have an actual database to check. On the other hand, we&#8217;re not actually writing any code to do the database update. Rather, we&#8217;re relying on Backbone to handle that interaction. That suggests a unit test strategy for this test case. All we need to know is that Backbone models use the <code>save()</code> method to update whatever backing store is persisting the model. In our case that backing store is the database. Here is the unit test code we can use:</p><pre class="brush: jscript; title: ; notranslate">
describe(&quot;Persistence&quot;, function() {
  beforeEach(function() {
    this.todo = new todoApp.Todo();
    this.save_stub = sinon.stub(this.todo, &quot;save&quot;);
  })
  afterEach(function() {
    this.save_stub.restore();
  })
  it(&quot;should update server when title is changed&quot;, function() {
    this.todo.set(&quot;title&quot;, &quot;New Summary&quot;);
    this.save_stub.should.have.been.calledOnce;
  })
  it(&quot;should update server when status is changed&quot;, function() {
    this.todo.set('complete',true);
    this.save_stub.should.have.been.calledOnce;
  })
})
</pre><p>We&#8217;ve included some additional code before each test, and we&#8217;ve added a section of code to execute after each test. That extra code manages a sinon <code>stub</code>, a function that effectively nullifies another function in the code. In our case the stub nullifies the <code>save()</code> method of <code>this.todo</code>. With the stub in place, calls to the method won&#8217;t actually go to the Backnone library. Instead, sinon intercepts those calls and simply returns immediately. This behavior is important. If we tried to execute the actual Backbone <code>save()</code> method in a unit test environment, the call would fail because there would not be a database or server API available.</p><p>With the stub in place, our test cases can use it to verify the model&#8217;s behavior. In the first test case, we immediately set the todo&#8217;s <code>title</code> to a new value. Since that changes the <code>title</code> property, we want our model to update its backing store. To check that we simply verify that the stub was called. To get our model to pass these tests, we can look for change events and respond appropriately.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.Todo = Backbone.Model.extend({
  defaults: {
    title: &quot;&quot;,
    complete:  false
  },
  initialize: function() {
    this.on(&quot;change&quot;, function(){ this.save(); });
  }
})
</pre><h3>Testing the View</h3><p>Of course, our app won&#8217;t do anyone any good if it doesn&#8217;t actually display the todos to users, and that requires creating some HTML. We&#8217;ll use Backbone views for that functionality. In our trivial app, we simply wish to render each todo as a list item. Here are the test cases that will get us started.</p><pre class="brush: jscript; title: ; notranslate">
describe(&quot;Todo List Item View&quot;, function() {
  beforeEach(function(){
    this.todo = new todoApp.Todo({title: &quot;Summary&quot;});
    this.item = new todoApp.TodoListItem({model: this.todo});
  })
  it(&quot;render() should return the view object&quot;, function() {
    this.item.render().should.equal(this.item);
  });
  it(&quot;should render as a list item&quot;, function() {
    this.item.render().el.nodeName.should.equal(&quot;LI&quot;);
  })
})
</pre><p>We begin our tests of the view with two test cases. First we ensure that the view&#8217;s <code>render()</code> method returns the view itself. That&#8217;s a common and very convenient convention in Backbone because it allows method chaining. Our second test case verifies that the HTML element the render creates is a list item (<code>&lt;li&gt;</code>). The code necessary to pass these tests is a straightforward Backbone view.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.TodoListItem = Backbone.View.extend({
  tagName: &quot;li&quot;,
  render: function() {
    return this;
  }
})
</pre><p>Next, we can develop the detailed content of that list item view. As an example, we want the full list item to look something like the following.</p><pre class="brush: xml; title: ; notranslate">
&lt;li&gt;
  &lt;label&gt;
    &lt;input type='checkbox'/&gt;
    Summary
  &lt;/label&gt;
&lt;/li&gt;
</pre><p>For our test cases, we can take advantage of jQuery to extract individual elements from the view&#8217;s main element.</p><pre class="brush: jscript; title: ; notranslate">
describe(&quot;Todo List Item View&quot;, function() {
  beforeEach(function(){
    this.todo = new todoApp.Todo({title: &quot;Summary&quot;});
    this.item = new todoApp.TodoListItem({model: this.todo});
  })
  describe(&quot;Template&quot;, function() {
    beforeEach(function(){
      this.item.render();
    })
    it(&quot;should contain the todo title as text&quot;, function() {
      this.item.$el.text().should.have.string(&quot;Summary&quot;);
    })
    it(&quot;should include a label for the status&quot;, function() {
      this.item.$el.find(&quot;label&quot;).should.have.length(1);
    })
    it(&quot;should include an &lt;input&gt; checkbox&quot;, function() {
      this.item.$el.find(&quot;label&gt;input[type='checkbox']&quot;).should.have.length(1);
    })
    it(&quot;should be clear by default (for 'pending' todos)&quot;, function() {
      this.item.$el.find(&quot;label&gt;input[type='checkbox']&quot;).is(&quot;:checked&quot;).should.be.false;
    })
    it(&quot;should be set for 'complete' todos&quot;, function() {
      this.save_stub = sinon.stub(this.todo, &quot;save&quot;);
      this.todo.set(&quot;complete&quot;, true);
      this.item.render();
      this.item.$el.find(&quot;label&gt;input[type='checkbox']&quot;).is(&quot;:checked&quot;).should.be.true;
      this.save_stub.restore();
    })
  })
})
</pre><p>Notice that in the last test case we&#8217;ve stubbed the model&#8217;s <code>save()</code> method. Since we&#8217;re changing a property from its default value, our model will dutifully try to persist that change to its backing store. In a unit test environment, however, we won&#8217;t have a database or a server API. The stub takes the place of the missing components and allows the tests to proceed without error. To get these tests to pass, we&#8217;ll have to add some additional code to our view.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.TodoListItem = Backbone.View.extend({
  tagName: &quot;li&quot;,
  template: _.template(
    &quot;&lt;label&gt;&quot;
    +   &quot;&lt;input type='checkbox' &lt;% if(complete) print('checked') %&gt;/&gt;&quot;
    +   &quot; &lt;%= title %&gt; &quot;
    + &quot;&lt;/label&gt;&quot;),
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
})
</pre><h3>Testing Model/View Interactions</h3><p>Now that we&#8217;ve verified that our view implementation creates the right HTML markup, we can test its interaction with our model. In particular, we want to make sure that users can toggle a todo&#8217;s status by clicking on the checkbox. Our test environment doesn&#8217;t require an actual human user, so we&#8217;ll use jQuery to generate the click event. To do that, however, we&#8217;ll have to add content to a real live DOM. That content is known as a test <em>fixture</em>. Here is the unit test code.</p><pre class="brush: jscript; title: ; notranslate">
describe(&quot;Todo List Item View&quot;, function() {
  beforeEach(function(){
    this.todo = new todoApp.Todo({title: &quot;Summary&quot;});
    this.item = new todoApp.TodoListItem({model: this.todo});
    this.save_stub = sinon.stub(this.todo, &quot;save&quot;);
  })
  afterEach(function() {
    this.save_stub.restore();
  })
  describe(&quot;Model Interaction&quot;, function() {
    it(&quot;should update model when checkbox clicked&quot;, function() {
      $(&quot;&lt;div&gt;&quot;).attr(&quot;id&quot;,&quot;fixture&quot;).css(&quot;display&quot;,&quot;none&quot;).appendTo(&quot;body&quot;);
      this.item.render();
      $(&quot;#fixture&quot;).append(this.item.$el);
      this.item.$el.find(&quot;input&quot;).click();
      this.todo.get('complete').should.be.true;
      $(&quot;#fixture&quot;).remove();
    })
  })
})
</pre><p>Notice that we&#8217;re once again stubbing the todo&#8217;s <code>save()</code> method. Otherwise, Backbone will try to update a non-existent backing store when we change the todo status with our simulated click.</p><p>For the test case itself, we begin by creating a <code>&lt;div&gt;</code> element with an <code>id</code> of <code>fixture</code> and we add that element to our live document. The live document, in this case, is the web page displaying the results of our tests. Although we remove the element immediately after verifying the test case, we also set its <code>display</code> property to <code>none</code> so it won&#8217;t interfere with Mocha&#8217;s display of the test results. The code that implements this functionality includes a small addition to the todo model. The addition is a new <code>toggleStatus()</code> method.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.Todo = Backbone.Model.extend({
  defaults: {
    title: &quot;&quot;,
    complete:  false
  },
  initialize: function() {
    this.on(&quot;change&quot;, function(){ this.save(); });
  },
  toggleStatus: function() {
    this.set(&quot;complete&quot;,!this.get(&quot;complete&quot;&quot;));
  }
})
</pre><p>In the view, we want to catch click events on the <code>&lt;input&gt;</code> element and call this method for the model.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.TodoListItem = Backbone.View.extend({
  tagName: &quot;li&quot;,
  template: _.template(
    &quot;&lt;label&gt;&quot;
    +   &quot;&lt;input type='checkbox' &lt;% if(complete) print('checked') %&gt;/&gt;&quot;
    +   &quot; &lt;%= title %&gt; &quot;
    + &quot;&lt;/label&gt;&quot;),
  events: {
    &quot;click input&quot;: &quot;statusChanged&quot;
  },
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  },
  statusChanged: function() {
    this.model.toggleStatus();
  }
})
</pre><h3>Testing the Collection</h3><p>At this point our application is nearly complete. The only remaining functionality is collecting all the todos together. Naturally, we&#8217;ll use a Backbone collection. We&#8217;re actually not going to do anything special with our collection, so we don&#8217;t really need any unit tests.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.Todos = Backbone.Collection.extend({
  model: todoApp.Todo,
  url:   &quot;api/todos&quot;
})
</pre><p>We can, however, verify that our implementation of the collection&#8217;s view is appropriate. We want that view rendered as an unordered list (<code>&lt;ul&gt;</code>). The test cases don&#8217;t require any functionality that we haven&#8217;t seen before.</p><pre class="brush: jscript; title: ; notranslate">
describe(&quot;Todos List View&quot;, function() {
  beforeEach(function(){
    this.todos = new todoApp.Todos([
      {title: &quot;Todo 1&quot;},
      {title: &quot;Todo 2&quot;}
    ]);
    this.list = new todoApp.TodosList({collection: this.todos});
  })
  it(&quot;render() should return the view object&quot;, function() {
    this.list.render().should.equal(this.list);
  });
  it(&quot;should render as an unordered list&quot;, function() {
    this.list.render().el.nodeName.should.equal(&quot;UL&quot;);
  })
  it(&quot;should include list items for all models in collection&quot;, function() {
    this.list.render();
    this.list.$el.find(&quot;li&quot;).should.have.length(2);
  })
})
</pre><p>The view implementation is also straightforward. It tracks any additions to the collection and updates the view. For the initial <code>render()</code> it simply adds all the models in the collection one at a time.</p><pre class="brush: jscript; title: ; notranslate">
todoApp.TodosList = Backbone.View.extend({
  tagName: &quot;ul&quot;,
  initialize: function() {
    this.collection.on(&quot;add&quot;, this.addOne, this);
  },
  render: function() {
    this.addAll();
    return this;
  },
  addAll: function() {
    this.collection.each(this.addOne, this);
  },
  addOne: function(todo) {
    var item = new todoApp.TodoListItem({model: todo});
    this.$el.append(item.render().el);
  }
})
</pre><h3>Bonus Tests: Verifying the API</h3><p>Because our REST API perfectly matches the API that Backbone expects, we didn&#8217;t need any custom code to manage the API interaction. As a result, we don&#8217;t need any unit test cases. In the real world, you might not be quite as lucky. If your API doesn&#8217;t conform to Backbone conventions, you may need to override or extend some of the Backbone code to deal with the non-standard API. That extra code will need unit tests as well. Fortunately, it&#8217;s relatively easy to test API interactions, even in a unit test environment.</p><p>The easiest way to test API interactions relies on the fake server functionality of Sinon.JS. Unfortunately, that functionality is only available (currently) in Sinon&#8217;s browser implementation. It is explicitly excluded from the node.js implementation. There are some hacks to get it running in node.js, but those hacks are quite brittle and rely on internal implementation details. It would be best to avoid them if possible. Fortunately, we can get by without Sinon&#8217;s fake server.</p><p>The secret is knowing that Backbone relies on jQuery&#8217;s <code>$.ajax()</code> function to implement REST APIs. We can intercept the API interactions by stubbing that function. When we stub the function, we&#8217;ll want to substitute our own response.  The <code>yieldsTo()</code> method of the stub gives us exactly that opportunity. It tells sinon what additional action it should take when the stub is called. Here&#8217;s a complete test case to verify that our collection correctly initializes itself using the REST API.</p><pre class="brush: jscript; title: ; notranslate">
describe(&quot;Collection's Interaction with REST API&quot;, function() {
  it(&quot;should load using the API&quot;, function() {
    this.ajax_stub = sinon.stub($, &quot;ajax&quot;).yieldsTo(&quot;success&quot;, [
      { id: 1, title: &quot;Mock Summary 1&quot;, complete: false },
      { id: 2, title: &quot;Mock Summary 2&quot;, complete: true  }
    ]);
    this.todos = new todoApp.Todos();
    this.todos.fetch();
    this.todos.should.have.length(2);
    this.todos.at(0).get('title').should.equal(&quot;Mock Summary 1&quot;);
    this.todos.at(1).get('title').should.equal(&quot;Mock Summary 2&quot;);
    this.ajax_stub.restore();
  })
})
</pre><h3>Finished!</h3><p>As you can see from the screen shot that follows, we&#8217;ve now written code that passes all the unit test cases. For the time being at least, development is complete.</p><p>[image src="http://jspro.com/files/2013/02/08-jstest-browser-all.png"]</p><h2>Testing During Integration</h2><p>Now that client-side development of our app is complete (and we have the tests to prove it), we can safely tuck our JavaScript into a source code management system. It can then be integrated into the build process for the entire application. As part of that process, we want to execute all the test cases we&#8217;ve developed. That will ensure that the code that makes up the final deployment passes all the tests that we&#8217;ve defined. It will also protect against &quot;minor tweaks&quot; to the code that inadvertently introduce new bugs.</p><p>During the build process, we&#8217;ll likely want to execute our tests from the command line rather than in a web browser. We don&#8217;t need the details of individual test cases, just an assurance that they all pass. Node.js makes it easy enough to accommodate this requirement. We only need to make a few small additions to our source code and unit test code files.</p><p>Our code needs these modifications because node.js handles global variables differently than web browsers. In a web browser, JavaScript variables are, by default, global in scope. Node.js, on the other hand, confines variables to their local module by default. In that environment, our code won&#8217;t be able to find the third-party libraries it needs (jQuery, Underscore, and Backbone. If we add the following statements at the beginning, though, node.js will resolve references to these libraries appropriately. We&#8217;ve constructed these statements so that they do no harm in the web browser, so we can leave them in the code permanently.</p><pre class="brush: jscript; title: ; notranslate">
var jQuery   = jQuery   || require(&quot;jquery&quot;);
var _        = _        || require(&quot;underscore&quot;);
var Backbone = Backbone || require(&quot;backbone&quot;);
Backbone.$   = jQuery;
</pre><p>We also need to adjust our test code. The test scripts need access to their own libraries (jQuery, Chai, Sinon.JS, and sinon-chai). In addition, we need to add a little extra to simulate a web browser&#8217;s Document Object Model (DOM). Recall that our tests for click handling required us to temporarily add a &quot;fixture&quot; <code>&lt;div&gt;</code> to the web page. Node.js, of course, doesn&#8217;t normally have a web page. The jsdom node package, however, lets us emulate one. The code below creates a minimal, simulated web page for our tests.</p><pre class="brush: jscript; title: ; notranslate">
if (typeof exports !== 'undefined' &amp;&amp; this.exports !== exports) {
  global.jQuery = require(&quot;jquery&quot;);
  global.$ = jQuery;
  global.chai = require(&quot;chai&quot;);
  global.sinon = require(&quot;sinon&quot;);
  chai.use(require(&quot;sinon-chai&quot;));
  global.jsdom = require(&quot;jsdom&quot;).jsdom;
  var doc = jsdom(&quot;&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;&quot;);
  global.window = doc.createWindow();
}
</pre><p>The conditional that wraps these statements tests to see if we&#8217;re running in the node.js environment instead of a web browser. In a browser, the extra statements aren&#8217;t necessary, so we can safely skip them.</p><p>With those changes, we can execute the full test suite from the command line. Simply navigate to the project&#8217;s root folder and execute the command <code>mocha</code>. The result looks quite familiar.</p><p>[image src="http://jspro.com/files/2013/02/09-jstest-node.png"]</p><p>Of course, <code>mocha</code> returns an exit level to indicate whether or not all of the tests passed. That lets us automate the tests as part of a continuous integration process, or simply as a local pre-commit script to preserve our own sanity.</p><h2>Conclusion</h2><p>At this point we have accomplished our goals. We have a unit test environment that runs in the background during development and immediately notifies us when any test fails. The tests execute in a web browser, giving us full access to the browser&#8217;s development tools while we&#8217;re coding. The same tests also run equally well from a command line script, so we can automate their execution during the build or integration process.</p><h2>Resources</h2><p>Here are the main unit test resources used in the article.</p><ul><li>Command line JavaScript execution environment: <a
href="http://nodejs.org/">node.js</a></li><li>JavaScript unit testing framework: <a
href="http://visionmedia.github.com/mocha/">Mocha</a></li><li>Test Development Environment: <a
href="https://github.com/airportyh/testem">Test&#8217;em</a></li><li>JavaScript assertion library: <a
href="http://chaijs.com/">Chai Assertion Library</a></li><li>Spies, stubs, and mocks: <a
href="http://sinonjs.org/">Sinon.JS</a></li><li>Additional assertions: <a
href="https://github.com/domenic/sinon-chai">Sinon.JS Assertions for Chai</a></li></ul><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/unit-testing-backbone-js-applications/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Introducing the Geeksphone by Mozilla</title><link>http://www.sitepoint.com/introducing-the-geeksphone-by-mozilla/</link> <comments>http://www.sitepoint.com/introducing-the-geeksphone-by-mozilla/#comments</comments> <pubDate>Sat, 26 Jan 2013 10:00:36 +0000</pubDate> <dc:creator>Colin Ihrig</dc:creator> <category><![CDATA[Advanced]]></category> <category><![CDATA[APIs]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[Mobile Tutorials & Articles]]></category> <guid
isPermaLink="false">http://jspro.com/?p=1946</guid> <description><![CDATA[Mozilla has been hard at work on their new operating system, Firefox OS. This week they took another step towards legitimacy with the announcement of developer preview devices &#8211; known as the Geeksphone. This article introduces Firefox OS and the Geeksphone to the JSPro audience. Firefox OS, also known as Boot to Gecko or B2G, [...]]]></description> <content:encoded><![CDATA[<p></p><p>Mozilla has been hard at work on their new operating system, <a
href="http://www.mozilla.org/en-US/firefoxos/" title="Mozilla - Firefox OS" target="_blank">Firefox OS</a>. This week they took another step towards legitimacy with the announcement of developer preview devices &#8211; known as the <a
href="http://www.geeksphone.com/" title="Geeksphone. Say 'hola' to the future" target="_blank">Geeksphone</a>. This article introduces Firefox OS and the Geeksphone to the JSPro audience.<br
/> <span
id="more-63970"></span></p><p>Firefox OS, also known as <em>Boot to Gecko</em> or <em>B2G</em>, is a completely open source operating system designed around HTML5 standards. Under the Firefox OS model, every app is a web app. This means a few things. First, the learning curve is significantly smaller. There&#8217;s no need to learn a new language. Second, tying into the principles behind Mozilla, there is no proprietary app store. This means not being a slave to companies like Apple.</p><h2>Development APIs</h2><p>One of the most exciting aspects of Firefox OS is the variety of advanced APIs used to interact with the underlying device. These APIs, collectively known as the WebAPI, combine W3C standards with Mozilla&#8217;s own specifications. For example, WebAPI developers can access the phone&#8217;s address book using Mozilla&#8217;s Contacts API and control the phone&#8217;s vibration hardware using the W3C <a
href="http://jspro.com/apis/the-buzz-about-the-vibration-api/" title="The Buzz About the Vibration API" target="_blank">Vibration API</a>. The full list of current and future APIs is available on the <a
href="https://wiki.mozilla.org/WebAPI" title="WebAPI - MozillaWiki" target="_blank">WebAPI Mozilla Wiki</a> page.</p><h2>Geeksphone Devices</h2><p>Currently there are two phone slated for release &#8211; the Keon and the Peak. The Keon is the lower end model, while the Peak is slightly more powerful and targeted at &#8220;those who like to be one step beyond.&#8221; The specs of both phones are listed below.</p><p><strong>Keon</strong><br
/> CPU Qualcomm Snapdragon S1 7225AB 1Ghz.<br
/> UMTS 2100/1900/900 (3G HSPA).<br
/> GSM 850/900/1800/1900 (2G EDGE).<br
/> Screen 3.5&#8243; HVGA Multitouch.<br
/> Camera 3 MP.<br
/> 4 GB (ROM) and 512 (RAM).<br
/> MicroSD, Wifi N, Light &amp; Prox. Sensor, G-Sensor, GPS, MicroUSB.<br
/> Battery 1580 mAh.</p><p><strong>Peak</strong><br
/> CPU Qualcomm Snapdragon S4 8225 1.2Ghz x2.<br
/> UMTS 2100/1900/900 (3G HSPA).<br
/> GSM 850/900/1800/1900 (2G EDGE).<br
/> Screen 4.3&#8243; qHD IPS Multitouch.<br
/> Camera 8 MP (back) + 2 MP (front).<br
/> 4 GB (ROM) and 512 (RAM).<br
/> MicroSD, Wifi N, Light &amp; Prox. Sensor, G-Sensor, GPS, MicroUSB, Flash (camera).<br
/> Battery 1800 mAh.</p><h2>Getting Involved</h2><p>There are several ways to get involved with the B2G project. You can install the <a
href="https://hacks.mozilla.org/2012/12/firefox-os-simulator-1-0-is-here/" title="Firefox OS Simulator 1.0 is here!" target="_blank">Firefox OS simulator</a>, or actually booth the operating system on your own hardware. Soon you&#8217;ll be able to purchase one of the developer preview phones discussed above. No matter which route you take, you will definitely want to read over Mozilla&#8217;s <a
href="https://developer.mozilla.org/en-US/docs/Apps/Getting_Started" title="Getting started with making apps - Apps | MDN" target="_blank">getting started guide</a>.</p><h2>Conclusion</h2><p>Only time will tell if Firefox OS is the next big thing or a bust. Some think that the completely open source nature of the project will help it succeed. Others feel that iOS and Android are simply too entrenched for another player to make much of a difference. However, it is certainly possible for Firefox OS to leave its mark, even if it isn&#8217;t the dominant player in the market &#8211; much like the Firefox browser.</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/introducing-the-geeksphone-by-mozilla/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Ten Useful JavaScript Libraries and jQuery Plugins for Web Developers</title><link>http://www.sitepoint.com/10-useful-javascript-libraries-and-jquery-plugins-for-web-developers/</link> <comments>http://www.sitepoint.com/10-useful-javascript-libraries-and-jquery-plugins-for-web-developers/#comments</comments> <pubDate>Mon, 14 Jan 2013 09:00:25 +0000</pubDate> <dc:creator>Syed Fazle Rahman</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[libraries]]></category> <category><![CDATA[plugins]]></category> <guid
isPermaLink="false">http://jspro.com/?p=1789</guid> <description><![CDATA[Whether you are a novice front end designer or an experienced web developer, every one of us has faced a situation where we write hundred lines of code and nothing seems to run as expected. If you have experience working in JavaScript and jQuery, then you might understand how troublesome it is to find a [...]]]></description> <content:encoded><![CDATA[<p></p><p>Whether you are a novice front end designer or an experienced web developer, every one of us has faced a situation where we write hundred lines of code and nothing seems to run as expected. If you have experience working in JavaScript and jQuery, then you might understand how troublesome it is to find a simple bug which was left behind unintentionally.<br
/> <span
id="more-63964"></span></p><p>Thus, we turn to pre-coded libraries and plugins. These utilities help us solve some specific problem by simply including them in our programs. They were made to solve some frequently occurring problems for developers. It is always good to have them bookmarked or downloaded in a local folder for future use. This article presents ten of the best JavaScript libraries and jQuery plugins developed to solve some of the most frequently occurring tasks in a website&#8217;s interface.</p><h1>#1 jQuery File Upload</h1><p>[image src="http://jspro.com/files/2013/01/JQueryFileUpload.jpg" href="https://github.com/blueimp/jQuery-File-Upload"]</p><p>As the name suggest, jQuery File Upload is a jQuery plugin used as a widget in web pages for uploading files. Some of the best features of this plugin are simultaneous uploading of multiple files, progress bar display, drag and drop from the desktop, cancel and resume of uploads, image previews while uploading, etc. This plugin also supports chunked upload, which means larger files can be uploaded in smaller parts. It is compatible with any server side platform like PHP, Ruby, Python, Node.js, etc.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><p><a
href="https://github.com/blueimp/jQuery-File-Upload">Source code</a></p><h1>#2 Ideal Forms</h1><p>[image src="http://jspro.com/files/2013/01/IdealForms.jpg" href="http://elclanrs.github.com/jq-idealforms/"]</p><p>Ideal Forms is a jQuery plugin for building HTML5 compatible forms. It supports form validation, customizable input types (select, file, radio, and checkbox), keyboard support, localization, custom datepicker using jQuery UI (fallback). This plugin works on Google Chrome, Opera, Firefox, IE8+, iOS5+, and Android 4.0+ browsers.</p><p><a
href="http://elclanrs.github.com/jq-idealforms/">Source Code</a></p><h1>#3 Form Accordion</h1><p>[image src="http://jspro.com/files/2013/01/FormAccordion.jpg" href="https://github.com/OliverJAsh/FormAccordion"]</p><p>Form Accordion is a jQuery plugin used for hiding and displaying related fields conditionally. This plugin can save you lots of time when building a form for a wide range of audiences. You can add conditions to specify which field to appear next if a particular value is selected in the current field.</p><p><a
href="https://github.com/OliverJAsh/FormAccordion">Source Code</a></p><h1>#4 TextExt Plugin</h1><p>[image src="http://jspro.com/files/2013/01/TextExtPlugin.png" href="http://textextjs.com/"]</p><p>TextExt Plugin is also a jQuery plugin that allows you to easily fill HTML text fields with suggestions. As you start typing in the text input field this plugin will show you a predefined set of suggestions matching what you have typed. TextExt is a great tool for making searches faster in web pages.</p><p><a
href="http://textextjs.com/">Source code</a></p><h1>#5 Sisyphus.js</h1><p>[image src="http://jspro.com/files/2013/01/Sisyphus.png" href="http://simsalabim.github.com/sisyphus/"]</p><p>Sisyphus.js is a script which helps visitors store form data locally in the browser. This script comes to the rescue when you are filling out a large form and all of a sudden you hit the close button of the browser accidentally. This script will fill the forms out for you automatically the next time you reload the page. This script is supported in Google Chrome 4+, Firefox 3.5+, Opera 10.5+, Safari 4+, and IE8+. For older version of IE (6 and 7) you have to load jStorage before loading Sisyphus.js.</p><p><a
href="http://simsalabim.github.com/sisyphus/">Source Code</a></p><h1>#6 jQuery Credit Card Validator</h1><p>[image src="http://jspro.com/files/2013/01/jQueryCreditCardValidator.jpg" href="http://paweldecowski.github.com/jQuery-CreditCardValidator/"]</p><p>jQuery Credit Card Validator validates an input field every time the user inserts a value. It recognizes the card and highlights the card type when a correct number is provided. Some of the supported card types are American Express, Laser, Diners Club, JCB, Discover Card, Maestro, MasterCard, Visa, and Visa Electron.</p><p><a
href="http://paweldecowski.github.com/jQuery-CreditCardValidator/">Source code</a></p><h1>#7 FTColumnflow</h1><p>[image src="http://jspro.com/files/2013/01/FTColumnflow.jpg" href="https://github.com/ftlabs/ftcolumnflow"]</p><p>FTColumnflow is a JavaScript library that helps web designers fix inadequacies of CSS column layout. It is named so because it was developed by Financial Times as part of their website layout project. This library helps in managing complex newspaper/magazine style layout and has many important features like fixed position elements, configurable column widths and margins, grouping columns into pages, vertical and horizontal alignment, etc. FTColumnflow is compatible with Chrome 8+, Safari 5+, Firefox 10+, iOS 5+, Android ICS+, Playbook OS 2.0.1+, and IE 10+ browsers.</p><p><a
href="https://github.com/ftlabs/ftcolumnflow">Source code</a></p><h1>#8 FitText.js</h1><p>[image src="http://jspro.com/files/2013/01/fittext.jpg" href="http://fittextjs.com/"]</p><p>FitText is a jQuery plugin to achieve responsive font types in your website. It resizes the headings in your website as per the ratio. It ignores the font size and uses minFontSize and maxFontSize to make the font flexible. If you are building a responsive or fluid design then you can use this plugin to resize the headings.</p><p><a
href="http://fittextjs.com/">Source code</a></p><h1>#9 money.js</h1><p>[image src="http://jspro.com/files/2013/01/moneyJS.jpg" href="http://josscrowcroft.github.com/money.js/"]</p><p>money.js is a JavaScript library which allows your visitors to get correct and updated exchange rates for free. It uses the Open Exchange rate API as the source for the current exchange rate, but it also has features so you can change the source. This library can be used in any framework, application, or language as you wish. It is not restricted to JavaScript based projects only. The best thing about this plugin is that it charges you no fee. There are also no rate limits!</p><p><a
href="http://josscrowcroft.github.com/money.js/">Source code</a></p><h1>#10 gmaps.js</h1><p>[image src="http://jspro.com/files/2013/01/GMapsJS.jpg" href="http://hpneo.github.com/gmaps/"]</p><p>Grab the power of Google Maps with this simple JavaScript library called gmaps.js. It helps you write simple lines of code for specifying what you need and the rest is done by the script. It locates areas, adds markers, shows routes, and has many other features. Some of the features include polylines, overlays, GeoJSON Polygons, Routes Advanced, Geofences, fusion tables layers, KML and GeoRSS layers, overlay map types, street view panoramas, geolocation, and geocoding. This library also has a jQuery plugin for it. So, if you are using jQuery then you can continue to use it without any collision problems.</p><p><a
href="http://hpneo.github.com/gmaps/">Source code</a></p><h1>Conclusion</h1><p>We hope you will find these plugins and libraries useful for your work. We are looking forward to hearing from you. We will be back with another set of ten more useful JavaScript libraries and jQuery plugins very soon.</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/10-useful-javascript-libraries-and-jquery-plugins-for-web-developers/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Understanding RequireJS for Effective JavaScript Module Loading</title><link>http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/</link> <comments>http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/#comments</comments> <pubDate>Mon, 07 Jan 2013 09:00:14 +0000</pubDate> <dc:creator>Rakhitha Nimesh</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <guid
isPermaLink="false">http://jspro.com/?p=1693</guid> <description><![CDATA[Modular programming is used to break large applications into smaller blocks of manageable code. Module based coding eases the effort for maintenance and increases reusability. However, managing dependencies between modules is a major concern developers face throughout the application development process. RequireJS is one of the most popular frameworks around for managing dependencies between modules. [...]]]></description> <content:encoded><![CDATA[<p></p><p>Modular programming is used to break large applications into smaller blocks of manageable code. Module based coding eases the effort for maintenance and increases reusability. However, managing dependencies between modules is a major concern developers face throughout the application development process. RequireJS is one of the most popular frameworks around for managing dependencies between modules. This tutorial examines the need for modularized code, and shows how RequireJS can help.<br
/> <span
id="more-63959"></span></p><h2>Loading JavaScript Files</h2><p>Large applications often require a number of JavaScript files. Generally, they are loaded one by one using <code>&lt;script&gt;</code> tags. Additionally, each file can potentially be dependent on other files. The most common example would be jQuery plugins, which are all dependent upon the core jQuery library. Therefore, jQuery must be loaded before any of its plugins. Let&#8217;s look at a simple example of JavaScript file loading in real applications. Assume we have the following three JavaScript files.</p><p><strong><code>purchase.js</code></strong></p><pre class="brush: jscript; title: ; notranslate">
function purchaseProduct(){
  console.log(&quot;Function : purchaseProduct&quot;);
  var credits = getCredits();
  if(credits &gt; 0){
    reserveProduct();
    return true;
  }
  return false;
}
</pre><p><strong><code>products.js</code></strong><div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><pre class="brush: jscript; title: ; notranslate">
function reserveProduct(){
  console.log(&quot;Function : reserveProduct&quot;);
  return true;
}
</pre><p><strong><code>credits.js</code></strong></p><pre class="brush: jscript; title: ; notranslate">
function getCredits(){
  console.log(&quot;Function : getCredits&quot;);
  var credits = &quot;100&quot;;
  return credits;
}
</pre><p>In this example, we are trying to purchase a product. First, it checks whether enough credits are available to purchase the product. Then, upon credit validation, it reserves the product. Another script, <code>main.js</code>, initializes the code by calling <code>purchaseProduct()</code>, as shown below.</p><pre class="brush: jscript; title: ; notranslate">
  var result = purchaseProduct();
</pre><h3>What Can Go Wrong?</h3><p>In this example, <code>purchase.js</code> depends upon both <code>credits.js</code> and <code>products.js</code>. Therefore, those files need to be loaded before calling <code>purchaseProduct()</code>. So, what would happen if we included our JavaScript files in the following order?</p><pre class="brush: xml; title: ; notranslate">
&lt;script src=&quot;products.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;purchase.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;credits.js&quot;&gt;&lt;/script&gt;
</pre><p>Here, initialization is done before <code>credits.js</code> is loaded. This will result in the error shown below. And this example only requires three JavaScript files. In a much larger project, things can easily get out of control. That&#8217;s where RequireJS comes into the picture.</p><p>[image src="http://jspro.com/files/2012/12/requirejs-01.png" href="http://jspro.com/files/2012/12/requirejs-01.png" caption="Plain JavaScript Example" ]</p><h2>Introduction to RequireJS</h2><p>RequireJS is a well known JavaScript module and file loader which is supported in the latest versions of popular browsers. In RequireJS we separate code into modules which each handle a single responsibility. Additionally, dependencies need to be configured when loading files. Let&#8217;s get started by downloading <a
href="http://requirejs.org/docs/download.html">RequireJS</a>. Once downloaded, copy the file to your project folder. Let&#8217;s assume our project&#8217;s directory structure now resembles the following image.</p><p>[image src="http://jspro.com/files/2013/01/requirejs021.png" href="http://jspro.com/files/2013/01/requirejs021.png" caption="Folder Structure"]</p><p>All the JavaScript files, including the RequireJS file, are located inside the <code>scripts</code> folder. The file <code>main.js</code> is used for initialization, and the other files contain application logic. Let&#8217;s see how the scripts are included inside the HTML file.</p><pre class="brush: xml; title: ; notranslate">
&lt;script data-main=&quot;scripts/main&quot; src=&quot;scripts/require.js&quot;&gt;&lt;/script&gt;
</pre><p>This is the only code required to include files using RequireJS. You might be wondering what happened to the other files and how they are included. The <code>data-main</code> attribute defines the initialization point of the application. In this case, it is <code>main.js</code>. RequireJS uses <code>main.js</code> to look for other scripts and dependencies. In this scenario all the files are located in same folder. Using logic, you can move the files to any folder you prefer. Now, let&#8217;s take a look at <code>main.js</code>.</p><pre class="brush: jscript; title: ; notranslate">
require([&quot;purchase&quot;],function(purchase){
  purchase.purchaseProduct();
});
</pre><p>In RequireJS, all code is wrapped in <code>require()</code> or <code>define()</code> functions. The first parameter of these functions specifies dependencies. In the previous example, initialization is dependent on <code>purchase.js</code>, since it defines <code>purchaseProduct()</code>. Note that the file extension has been omitted. This is because RequireJS only considers <code>.js</code> files.</p><p>The second parameter to <code>require()</code> is an anonymous function which takes an object that is used to call the functions inside the dependent file. In this scenario, we have just one dependency. Multiple dependencies can be loaded using the following syntax.</p><pre class="brush: jscript; title: ; notranslate">
require([&quot;a&quot;,&quot;b&quot;,&quot;c&quot;],function(a,b,c){
});
</pre><h2>Creating Applications with RequireJS</h2><p>In this section we are going to convert the plain JavaScript example discussed in the previous section into RequireJS. We already covered <code>main.js</code>, so let&#8217;s move on to the other files.</p><p><strong><code>purchase.js</code></strong></p><pre class="brush: jscript; title: ; notranslate">
define([&quot;credits&quot;,&quot;products&quot;], function(credits,products) {
  console.log(&quot;Function : purchaseProduct&quot;);
  return {
    purchaseProduct: function() {
      var credit = credits.getCredits();
      if(credit &gt; 0){
        products.reserveProduct();
        return true;
      }
      return false;
    }
  }
});
</pre><p>First, we declare that purchase functionality depends on credits and products. Inside the <code>return</code> statement, we can define the functions of each module. Here, we have called the <code>getCredits()</code> and <code>reserveProduct()</code> functions on the objects passed. <code>product.js</code> and <code>credits.js</code> are similar, and are shown below.</p><p><strong><code>products.js</code></strong></p><pre class="brush: jscript; title: ; notranslate">
define(function(products) {
  return {
    reserveProduct: function() {
      console.log(&quot;Function : reserveProduct&quot;);
      return true;
    }
  }
});
</pre><p><strong><code>credits.js</code></strong></p><pre class="brush: jscript; title: ; notranslate">
define(function() {
  console.log(&quot;Function : getCredits&quot;);
  return {
    getCredits: function() {
      var credits = &quot;100&quot;;
      return credits;
    }
  }
});
</pre><p>Both of these files are configured as independent modules &#8211; meaning they are not dependent on anything. The important thing to notice is the use of <code>define()</code> instead of <code>require()</code>. Choosing between <code>require()</code> or <code>define()</code> depends on the structure of your code, and will be discussed in the following section.</p><h2>Using <code>require()</code> vs. <code>define()</code></h2><p>Earlier I mentioned that we can use both <code>require()</code> and <code>define()</code> to load dependencies. Understanding the difference between those two functions is essential to managing dependencies. The <code>require()</code> function is used to run immediate functionalities, while <code>define()</code> is used to define modules for use in multiple locations. In our example we need to run the <code>purchaseProduct()</code> function immediately. So, <code>require()</code> was used inside <code>main.js</code>. However, the other files are reusable modules and therefore use <code>define()</code>.</p><h2>Why RequireJS is Important</h2><p>In the plain JavaScript example, an error was generated due to the incorrect order of file loading. Now, delete the <code>credits.js</code> file in the RequireJS example and see how it works. The following image shows the output of the browser inspection tool.</p><p>[image src="http://jspro.com/files/2012/12/requirejs-03.png" href="http://jspro.com/files/2012/12/requirejs-03.png" caption="RequireJS Example"]</p><p>The difference here is that no code has been executed in the RequireJS example. We can confirm it since nothing is printed on the console. In the plain JavaScript example we had some output printed on the console before generating the error. RequireJS waits until all the dependent modules are loaded before executing the functionality. If any modules are missing, it doesn&#8217;t execute any code. This helps us maintain the consistency of our data.</p><h2>Managing the Order of Dependent Files</h2><p>RequireJS uses <strong>Asynchronous Module Loading</strong> (AMD) for loading files. Each dependent module will start loading through asynchronous requests in the given order. Even though the file order is considered, we cannot guarantee that the first file is loaded before the second file due to the asynchronous nature. So, RequireJS allows us to use the <code>shim</code> config to define the sequence of files which need to be loaded in correct order. Let’s see how we can create configuration options in RequireJS.</p><pre class="brush: jscript; title: ; notranslate">
requirejs.config({
  shim: {
    'source1': ['dependency1','dependency2'],
    'source2': ['source1']
  }
});
</pre><p>RequireJS allows us to provide configuration options using the <code>config()</code> function. It accepts a parameter called <code>shim</code> which we can use to define the mandatory sequences of dependencies. You can find the complete configuration guide in the <a
href="http://requirejs.org/docs/api.html#config">RequireJS API documentation</a>.</p><pre class="brush: jscript; title: ; notranslate">
define([&quot;dependency1&quot;,&quot;dependency2&quot;,&quot;source1&quot;,&quot;source2&quot;], function() {
);
</pre><p>Under normal circumstances these four files will start loading in the given order. Here, <code>source2</code> depends on <code>source1</code>. So, once <code>source1</code> has finished loading, <code>source2</code> will think that all the dependencies are loaded. However, <code>dependency1</code> and <code>dependency2</code> may still be loading. Using the shim config, it is mandatory to load the dependencies before <code>source1</code>. Hence, errors will not be generated.</p><h2>Conclusion</h2><p>I hope this tutorial helps you get started with RequireJS. Although it seems simple, it is really powerful in managing dependencies in large scale JavaScript applications. This tutorial alone is not enough to cover all the aspects of RequireJs, so I hope you learn all the advanced configurations and techniques using the official website.</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/understanding-requirejs-for-effective-javascript-module-loading/feed/</wfw:commentRss> <slash:comments>12</slash:comments> </item> <item><title>Package Management for the Browser with Bower</title><link>http://www.sitepoint.com/package-management-for-the-browser-with-bower/</link> <comments>http://www.sitepoint.com/package-management-for-the-browser-with-bower/#comments</comments> <pubDate>Mon, 31 Dec 2012 09:00:24 +0000</pubDate> <dc:creator>Ian Oxley</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[Bower]]></category> <category><![CDATA[Package Management]]></category> <guid
isPermaLink="false">http://jspro.com/?p=1425</guid> <description><![CDATA[Bower is a package manager for the browser. Developed by Twitter, and available via npm, it means the days of manually managing your client-side JavaScript packages could soon be a thing of the past. To install Bower you&#8217;ll need to have Node and NPM installed. You can download and install Node from nodejs.org. NPM comes [...]]]></description> <content:encoded><![CDATA[<p></p><p>Bower is a package manager for the browser. Developed by Twitter, and available via npm, it means the days of manually managing your client-side JavaScript packages could soon be a thing of the past.<br
/> <span
id="more-63954"></span></p><p>To install <a
href="http://twitter.github.com/bower/" class="broken_link">Bower</a> you&#8217;ll need to have Node and NPM installed. You can download and install Node from <a
href="http://nodejs.org">nodejs.org</a>. <a
href="https://npmjs.org/">NPM</a> comes bundled with each binary package, so when you install Node, NPM should automatically be installed at the same time. You&#8217;ll also need to have Git installed, as Bower uses Git endpoints to locate packages. If you don&#8217;t have Git installed, you can download it from <a
href="http://git-scm.com/downloads">git-scm.com/downloads</a>. Once you&#8217;ve got Node, npm, and Git installed, all you need to do now is open up your terminal and type:</p><pre><code>npm install bower -g</code></pre><p>If you&#8217;re new to NPM, the <code>-g</code> on the end means Bower will be installed globally, meaning we can run it from anywhere in any project directory. Let&#8217;s run Bower now and pass it the <code>--help</code> command to see exactly what it has to offer us:<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><pre><code>bower --help</code></pre><p>If you&#8217;re following along, you&#8217;ll see there&#8217;s commands to install, uninstall, and update packages, list the packages you&#8217;ve currently got installed, and search for new packages. We can also get help on any particular command by passing that command to <code>help</code>:</p><pre><code>bower help list</code></pre><p><code>bower list</code> simply lists the packages we&#8217;ve installed. If we run it right now, we won&#8217;t see much as we haven&#8217;t installed any packages yet. Let&#8217;s fix that by installing jQuery using the following command.</p><pre><code>bower install jquery</code></pre><p>When you run this, you&#8217;ll see that Bower clones the package&#8217;s Git repository, caches the package in the <code>~/bower</code> directory, then copies the package to our current project&#8217;s <code>components</code> directory (which Bower will create if it doesn&#8217;t exist). Once downloaded, the simplest way to include jQuery in your project is via a regular <code>&lt;script&gt;</code> tag, as shown below.</p><pre class="brush: xml; title: ; notranslate">
&amp;amp;lt;script src=&amp;amp;quot;components/jquery/jquery.js&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/script&amp;amp;gt;
</pre><p>Of course, you&#8217;re free to integrate Bower with your preferred choice of bundling / minification tool for more complex projects.</p><p>You&#8217;ll notice that jQuery was installed in it&#8217;s own directory, which itself contains <code>jquery.js</code> and a <code>components.json</code> file. The <code>components.json</code> file is much like the <code>package.json</code> file used in NPM modules. It stores meta data about the package, together with any dependencies that the package requires. The jQuery package doesn&#8217;t have any dependencies, but if we install a package that <em>does</em> have dependencies, Bower will install these at the same time. jquery-Mustache has a dependency on mustache, so let&#8217;s install that and see what happens:</p><pre><code>bower install jquery-Mustache</code></pre><p>You&#8217;ll see Bower download jquery-Mustache first, followed by it&#8217;s dependencies. We can verify this by looking in our components directory:</p><pre><code>ls components
jquery  jquery-Mustache  mustache</code></pre><p>jquery-Mustache we&#8217;d expect to see, and jQuery was already there from before, but, as you can see, Bower automatically downloaded mustache for us without us having to worry about it. If we look at the jquery-Mustache <code>components.json</code> file, we can see how dependencies are specified:</p><pre class="brush: jscript; title: ; notranslate">
&amp;amp;quot;dependencies&amp;amp;quot;: {
    &amp;amp;quot;jquery&amp;amp;quot;: &amp;amp;quot;&amp;amp;gt;=1.5&amp;amp;quot;,
    &amp;amp;quot;mustache&amp;amp;quot;: &amp;amp;quot;&amp;amp;gt;=0.4&amp;amp;quot;
}
</pre><p>When Bower reads this, it knows it must download at least version 1.5 of jQuery, and at least version 0.4 of mustache. If you run <code>bower list</code> now, you&#8217;ll see that Bower lists your installed packages, with their dependencies nested underneath them.</p><h2>Installing Multiple Packages</h2><p>You don&#8217;t have to install your packages one at a time: you can pass a space separated list to <code>bower install</code> and it&#8217;ll install each package one-by-one. Let&#8217;s install a few more jQuery plugins using the following command.</p><pre><code>bower install jquery.validation jquery.colorbox jquery.loadfeed</code></pre><h2>Uninstalling Packages</h2><p>Uninstalling packages is just as easy as installing them. In this case, we use the <code>bower uninstall</code> command.</p><pre><code>bower uninstall jquery.colorbox</code></pre><p>If you mistakenly uninstall a package that is a dependency of another package, Bower will warn you you&#8217;ve removed a dependency <em>after</em> uninstalling it. For example, you can uninstall jQuery using the following command.</p><pre><code>bower uninstall jquery</code></pre><p>When you uninstall jQuery, Bower warns you that <code>jquery.loadfeed depends on jquery</code>. Fortunately, it&#8217;s easy enough to reinstall jQuery.</p><h2>Managing Package Versions</h2><p>Updating packages is pretty painless too. To update jQuery to the latest version we&#8217;d type:</p><pre><code>bower update jquery</code></pre><p>And, to see which versions of a package are available, we can run the <code>bower info</code> command:</p><pre><code>bower info jquery</code></pre><h2>Publishing Packages</h2><p>Finally, let&#8217;s have a quick look at how easy it is to publish your own packages with Bower. Simply follow these three steps:</p><ol><li>Create your package&#8217;s <code>component.json</code> file</li><li>Push your package to a Git endpoint, e.g. GitHub.</li><li>Run <code>Bower register yourpackagename git://github.com/yourusername/repositoryname</code> replacing <code>yourpackagename</code>, <code>yourusername</code>, and <code>repositoryname</code> as appropriate.</li></ol><p>That&#8217;s all there is to it. You don&#8217;t have to create an account, or setup any authentication. Package names are allocated on a first come, first served basis. So, you&#8217;ll just need to come up with a unique name for your package, and then other developers will be able to install it by running <code>bower install yourpackagename</code>.</p><h2>Conclusion</h2><p>In this article we&#8217;ve had a look at Bower, the browser package manager developed by Twitter. We&#8217;ve gone through how to install Bower via npm, how to install, update, and delete packages, and how you can publish your own packages.</p><h2>Further Resources:</h2><ul><li><a
href="http://twitter.github.com/bower/" class="broken_link">Bower</a></li><li><a
href="https://github.com/twitter/bower">GitHub Repository</a></li><li><a
href="http://javascriptjabber.com/029-jsj-bower-js-with-alex-maccaw-and-jacob-thornton/">JavaScript Jabber 029: Bower.js with Alex MacCaw and Jacob Thornton</a></li><li><a
href="https://github.com/ender-js/Ender">Ender</a></li><li><a
href="http://jamjs.org">Jam</a></li></ul><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/package-management-for-the-browser-with-bower/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Knockout.js: An Introduction</title><link>http://www.sitepoint.com/knockout-js-an-introduction/</link> <comments>http://www.sitepoint.com/knockout-js-an-introduction/#comments</comments> <pubDate>Wed, 26 Dec 2012 09:00:22 +0000</pubDate> <dc:creator>Glenn Goodrich</dc:creator> <category><![CDATA[Beginner]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[knockout]]></category> <guid
isPermaLink="false">http://jspro.com/?p=1568</guid> <description><![CDATA[The rise of sophisticated web applications, such as GMail, has given birth to an army of JavaScript frameworks. These frameworks allow you to, basically, create a client-side application within your web application. Terms such as &#8220;MVC&#8221; and other design patterns, once saved for only the server-side of the web, are now applied to just the [...]]]></description> <content:encoded><![CDATA[<p></p><p>The rise of sophisticated web applications, such as GMail, has given birth to an army of JavaScript frameworks. These frameworks allow you to, basically, create a client-side application within your web application. Terms such as &#8220;MVC&#8221; and other design patterns, once saved for only the server-side of the web, are now applied to just the the client bits of your code. The more popular frameworks these days are <a
href="http://backbonejs.org" target="_blank">Backbone</a>, <a
href="http://emberjs.com" target="_blank">Ember</a>, and <a
href="http://knockoutjs.com" target="_blank">Knockout</a>. This article will take a whirlwind look at the latter.<br
/> <span
id="more-63950"></span></p><p>Knockout takes the <a
href="http://en.wikipedia.org/wiki/Model_View_ViewModel" target="_blank">Model-View-View-Model (MVVM)</a> approach to application architecture. MVVM is a architectural pattern that has (some of) its roots in Microsoft and their Windows Presentation Foundation/Silverlight/Failed Attempt at making ASP.NET Web Forms usable. Being honest, I avoided Knockout due to these roots, and I am guessing that many developers do as well. It wasn&#8217;t until I inherited an application that uses Knockout that I was forced to I actually learn about it.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><p>Yet again, I have been pleasantly surprised to know that my groundless developer bias was very wrong.</p><h2>At Least it&#8217;s Not MVC</h2><p>Looking at the <a
href="http://knockoutjs.com/index.html" target="_blank">Knockout home page</a>, the key concepts it lists are:</p><ul><li>Declaritive Bindings</li><li>Automatic UI Refresh</li><li>Dependence Tracking</li><li>Templating</li></ul><p>I am not going to run through each of these, as you have the same access to their site. I will say what I think it means, in a nutshell. As I see it, the strength of Knockout is it&#8217;s data-binding. If you&#8217;ve never used a framework that binds the UI to a model (the view model, it this case) the core concept is that any changes to that model are immediately reflected in the view/UI. Adobe Flex is, in my opinion, the most well-known data binding framework. Data binding is enormously powerful, especially if you have pieces of your model strewn about the UI. Updating a value in one place and having 10 UI elements change as a result will bring a smile to any trollface.</p><p>Data-binding is the sweetest sauce that Knockout provides, but it is more than that. The templating is very powerful, and you can use any JavaScript templating library you like (jQuery Templates, <a
href="http://jspro.com/toolsandlibraries/creating-html-templates-with-mustachejs/" title="Creating HTML Templates with Mustache.js" target="_blank">mustache</a>, etc). Knockout is also extensible, providing a plugin framework that we will take advantage of in the demo application I&#8217;ve put together to show Knockout in action.</p><h2>Lick it, Lick it Good</h2><p>The demo application is a simple, yet kind of disgusting, app called LinkLicker. The idea is that links are submitted and you lick the ones you like. Yes, I am a 4 year-old.</p><p>The server-side of this application is both a Rails app and irrelevant. Your server side application simply needs to spit back JSON, so it can be Sinatra or Rails or Cuba or whatever. I shant bore you with the details of the web app, but they are in the <a
href="http://github.com/rubysource/linklicker" target="_blank">github repository if you simply must know</a>.</p><p>The app shows a form that allows links to be submitted, a list of submitted links, and a list of links that have been licked by the current user. When a link has been licked, it&#8217;s icon changes. This, I am sure, is the next FacebookTwitter.</p><h3>Setup</h3><p>You will need the Knockout code available in your web app to make this work. I&#8217;ve put mine in the vendor directory, along with the most commonly used Knockout plugin. This plugin is the <a
href="http://knockoutjs.com/documentation/plugins-mapping.html" target="_blank">Knockout Mapping plugin</a>, and it takes all the hard work out of mapping JSON from the server to JavaScript objects on the client.  Note: I won&#8217;t really cover the Mapping plugin in this article, but the important bit is it creates observables out of all our JSON properties when it maps the objects. You&#8217;ll see what observables are shortly.</p><p>Structurally, I like to put each &#8220;model&#8221; class in it&#8217;s own file on the client. LinkLicker really only has one model: Link. I also like to have a global class that represents my application that I call, unremarkably, App. The final directory sturcture for the JavaScript looks like:</p><p>[image src="http://jspro.com/files/2012/12/img1.png" href="http://rubysource.com/?attachment_id=4882"]</p><h3>UI</h3><p>The UI for LinkLicker was driven heavily by my desire to do as little as possible while still getting the Knockout concepts across. As I mentioned above, there is a form, as well as three lists of links. The three lists are All Links, New (meaning, unlicked), and licked links. As you may have surmised, a link can be in more than one of these lists at any given time. The screenshot of the UI is below:</p><p>[image src="http://jspro.com/files/2012/12/img2.png" href="http://rubysource.com/?attachment_id=4883"]</p><h3>Bootstrap</h3><p>Bootstrapping LickLinker consists of binding to the form and creating our three lists. We&#8217;ll make all of these properties on our App. Easy stuff.</p><pre class="brush: jscript; title: ; notranslate">
var App = function() {
  this.newLink = ko.observable(new Link());
  this.mylinks = ko.observableArray();
  this.lickedLinks = ko.observableArray();
  this.allLinks = ko.observableArray();
};
</pre><p>You are likely wondering what all this <strong>observable</strong> madness be. When you make a property an observable, it becomes a super-powerful notifier of changes to that property. Knockout will keep track (as best it can, and it&#8217;s pretty good at it) of things that are interested in your property and notify then when it changes. The <a
href="http://knockoutjs.com/documentation/observables.html" target="_blank">Observables docs</a> on the Knockout site are great, and there are interactive tutorials to use as well.</p><p>In short, and if you can think ahead, when we bind our UI (form) to the newLink it will then notify our form of changes and vice-versa.</p><p>The other three properties are <strong>observableArrays</strong>. These are, conceptually, exactly the same as observables, except that they work on a collection. An observableArray will track what objects are in the array, and it has many helper methods to add and remove these objects. You can easily pop or push items onto an observableArray, slice it, get its length, reverse it, and many other methods you&#8217;d expect.</p><p>Again, since observables and observableArrays are notifiers of change, when we bind the lists in our UI to these lists of links, everything will be updated to reflect the latest state. Hopefully, this concept is sinking in.</p><h4>The Model</h4><p>The model for LinkLicker is just a link and it has 3 properties: url, description, and lickedByCurrentUser.</p><h4>The Form</h4><p>Knockout is all about data-binding, remember? As such, we can bind a new Link to the form and, then, as the user enters data it will populate this newly bound Link. In the code snippet above, we create our newLink property as an observable. Now, to bind it to the form:</p><pre class="brush: xml; title: ; notranslate">
&lt;form id=&quot;create_form&quot; class=&quot;one-third column alpha&quot; data-bind=&quot;submit: createNewLink&quot;&gt;
&lt;!-- ko with: newLink --&gt;
 &lt;label for=&quot;link_url&quot;&gt;Link:&lt;/label&gt;
 &lt;input id=&quot;link_url&quot; type=&quot;text&quot; name=&quot;link[url]&quot; data-bind=&quot;value: url&quot; /&gt;
 &lt;label for=&quot;description&quot;&gt;Description:&lt;/label&gt;
 &lt;input id=&quot;link_description&quot; type=&quot;text&quot; name=&quot;link[description]&quot; data-bind=&quot;value: description&quot; /&gt;
 &lt;!-- /ko --&gt;
 &lt;input type=&quot;submit&quot; value=&quot;Add&quot; /&gt;&lt;/form&gt;
</pre><p>In the above snippet, focus on the <code>&lt;!-- ko with: newLink --&gt;</code> line. Knockout offers a couple of different ways to bind parts of the DOM to the view model. This example uses &#8220;containerless bindings&#8221;, which means, it doesn&#8217;t create a DOM element for that declaration.</p><p>The other way to do it is to create a DOM element (such as a <code>div</code>) and add a <code>data-bind </code>attribute specifying the template. There are loads of examples on the Knockout site of the latter if you are confused.</p><p>That <code>ko with: newLink</code> tells Knockout to find the newLink property of whatever this view is bound to and scope everything within the block to it. This should be a bit clearer if you look at the <code>input</code> tags. Each input tag has a <code>data-bind</code> attribute that binds the value of that input to a property on newLink.</p><h4>The Ties the Bind</h4><p>With our UI in place, we need some mechanism to bind it to our view model. In this app, the view model is our global App class on the client. The App is bound to the view when the page is loaded, as shown here:</p><pre class="brush: jscript; title: ; notranslate">
$(function(){
  App.globalApp = new App();
  ko.applyBindings(App.globalApp);
  App.globalApp.loadLinks();
});
</pre><p>Easy peasy.</p><p>Filtering a list can be done by creating two &#8220;computeds&#8221; (formerly dependentObservables). Here, let me show you:</p><pre class="brush: jscript; title: ; notranslate">
this.allLinks = ko.observableArray();
this.lickedLinks = ko.computed(function() {
  return this.allLinks().filter(function(link) {
    return link.isLicked();
  });
}, this);
this.newLinks = ko.computed(function() {
  return this.allLinks().filter(function(link) {
    return !link.isLicked();
  });
}, this);
</pre><p>A <code>computed</code> is an observable that depends on the values of other observables. You can see that we filter the allLinks observableArray based on the value of isLicked() for each link. The second argument to the computed (<code>this</code>) is the context to bind the function.</p><p>Computeds are enormously helpful and you&#8217;ll find yourself using them everywhere.</p><h4>Extending KnockoutJS</h4><p>While Knockout has many, many bindings that you can use, such as text, html, css, visible, you will find occasions that require a new binding. Writing a custom binding is very simple. As an example, I am going to write a <code>hidden</code> binding which is the opposite of the <code>visible</code> binding. It&#8217;s is below:</p><pre class="brush: jscript; title: ; notranslate">
ko.bindingHandlers.hidden = {
  update: function(element, valueAccessor){
    var value = ko.utils.unwrapObservable(valueAccessor());
    ko.bindingHandlers.visible.update(element, function() {
      return !value;
    });
  }
};
</pre><p>In the binding, I grab the value of the element being bound, and then pass it to the existing <code>visible</code> binding. The result is negated and returned.</p><p>Obviously, this is a trivial binding, but you can get very complex if needed. Google will show you bindings for jQuery UI elements, for example, along with thousands of other custom bindings that the community has authored.</p><h2>Momma Said Wrap This Up!</h2><p>There were many other aspects of Knockout I would like to cover, but I think we&#8217;ve taken a nice look across many of it&#8217;s features. Hopefully, when you are evaluating JavaScript frameworks, this article will help you make a decision.</p><p>Remember, the entirety of the LinkLicker source is yours to browse, use, mock, whatever on <a
href="http://github.com/rubysource/linklicker" target='_blank'>github</a>.</p><p>If you have questions on LinkLicker or Knockout, hit me in the comments. Thanks for reading!</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/knockout-js-an-introduction/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Creating HTML Templates with Mustache.js</title><link>http://www.sitepoint.com/creating-html-templates-with-mustachejs/</link> <comments>http://www.sitepoint.com/creating-html-templates-with-mustachejs/#comments</comments> <pubDate>Mon, 10 Dec 2012 09:00:47 +0000</pubDate> <dc:creator>Rakhitha Nimesh</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[Mustache.js]]></category> <category><![CDATA[Templating]]></category> <guid
isPermaLink="false">http://jspro.com/?p=1300</guid> <description><![CDATA[Web applications use MVC architectures to separate business logic from the presentation views. Complex projects which involves large amounts of client side HTML manipulation with JavaScript can be difficult to maintain. In such scenarios we can use template systems to increase reusability and ease the task of managing views. Mustache.js provides a well documented template [...]]]></description> <content:encoded><![CDATA[<p></p><p>Web applications use MVC architectures to separate business logic from the presentation views. Complex projects which involves large amounts of client side HTML manipulation with JavaScript can be difficult to maintain. In such scenarios we can use template systems to increase reusability and ease the task of managing views. Mustache.js provides a well documented template system which can be used to manage your templates. And, since mustache supports various languages, we don&#8217;t need a separate templating system on the server side. This article covers the basics of working with mustache.<br
/> <span
id="more-1300"></span></p><h2>Why We Need Template Systems</h2><p>Most developers that are not aware of template systems create new chunks of HTML code and dynamically insert them into the DOM using JavaScript. A common way of doing this is to specify the HTML elements in a string and then set the <code>innerHTML</code> property or call the jQuery <code>html()</code> method. An example of this technique is shown below.</p><pre class="brush: jscript; title: ; notranslate">
var dynamic_html = &quot;&lt;div&gt;&lt;span&gt;Highlighted&lt;/span&gt;&lt;span&gt;Author&lt;/span&gt;&lt;/div&gt;&quot;;
document.getElementByID(&quot;container&quot;).innerHTML = dynamic_html;
</pre><p>Another method for building the DOM is to create elements and append them individually, as shown below.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><pre class="brush: jscript; title: ; notranslate">
var title = document.createElement('div');
var highlight = document.createElement('span');
var highlight_text = document.createTextNode(&quot;Highlight&quot;);
var author = document.createElement('span');
var author_text = document.createTextNode(&quot;Author&quot;);
var container = document.getElementById('container');
highlight.appendChild(highlight_text);
title.appendChild(highlight);
author.appendChild(author_text);
title.appendChild(author);
container.appendChild(title);
</pre><p>Both the methods above can be used effectively to add elements dynamically into your document. Consider a situation where we have a very well designed bullet list which needs to be used across three different types of pages in our site. Using these techniques, we would have to repeat the HTML code the list in three different locations. This is generally considered to be bad coding practice.</p><p>In such scenarios we can use predefined templates in different locations without repeating the code. Mustache.js is a very popular template engine using JavaScript. Since mustache provides both server side and client side templates for numerous languages, we don&#8217;t have to worry about choosing separate template engines.</p><h2>Getting Started with Mustache.js</h2><p>Mustache is an open source logic-less template system developed for languages such as JavaScript, Ruby, Python, PHP, and Java. You can grab a copy of the library by visiting the <a
href="https://github.com/janl/mustache.js" target="_blank">official page on GitHub</a>. Mustache provides templates and views as the basis for creating dynamic templates. Views contain the data to be included in the templates as JSON. Templates contain the presentation HTML or data with the template tags for including view data. Earlier, we mentioned mustache as logic-less. This means the templates will not contain any <code>if-else</code> conditions or <code>for</code> loops. Now, let&#8217;s get started on mustache templates using a simple example.</p><pre class="brush: xml; title: ; notranslate">
&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;title&gt;Mustache.js Inline Method&lt;/title&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;mustache.js&quot; &gt;&lt;/script&gt;
    &lt;script&gt;
      var view = {
        name : &quot;Joe&quot;,
        occupation : &quot;Web Developer&quot;
      };
      function loadtemp(){
        var output = Mustache.render(&quot;{{name}} is a  {{occupation}}&quot;, view);
        document.getElementById('person').innerHTML = output;
      }
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body onload=&quot;loadtemp()&quot; &gt;
    &lt;p id=&quot;person&quot;&gt;&lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre><p>First, we need to include the mustache.js file in the document. Then we can work on creating mustache templates. In the above example we have a view containing the name and occupation of a person. Then, we have the template inside the <code>render()</code> function with presentation code and tags for name and occupation data. Tags are indicated by the double braces, or mustaches, that surround them. Now, let&#8217;s take a look at how the <code>render()</code> method works.</p><h3>Rendering Mustache Templates</h3><p>The following code shows the implementation of the <code>render()</code> function inside the mustache.js file. Three parameters can be passed to <code>render()</code>. The first two parameters, <code>template</code> and <code>view</code> are mandatory. <code>partials</code> can be considered as dynamic templates which you can inject into your main template. In our previous example, we passed the template as an inline parameter and the view as the second parameter, and assigned the result to the <code>output</code> variable.</p><pre class="brush: jscript; title: ; notranslate">
Writer.prototype.render = function (template, view, partials) {
  return this.compile(template)(view, partials);
};
</pre><p>This is the most basic form of templating with mustache. Let&#8217;s see the other methods available for creating more organized code.</p><h2>Defining Mustache Templates</h2><p>There are various methods for defining mustache templates in your application. These methods are similar to including CSS using inline styles, inline stylesheets, and external stylesheets. The example we discussed earlier can be considered as an inline method since we are passing the template directly to the function. This method prevents the possibility of reusable templates. Let&#8217;s see how we can define templates as inline script templates as opposed to directly passing to the function.</p><h3>Templates as Inline Scripts</h3><p>We can define template data inside of a <code>&lt;script&gt;</code> tag and include it in the HTML document. To prevent the browser from executing the template code, we must change the MIME type to something other than <code>text/javascript</code>. Some common MIME types are <code>text/html</code> , <code>text/template</code>, and <code>text/mustache</code>. The following example is a simple template using this method.</p><pre class="brush: jscript; title: ; notranslate">
&lt;script id=&quot;sample_template&quot; type=&quot;text/html&quot;&gt;
&lt;h1&gt;{{name}}&lt;/h1&gt;
&lt;/script&gt;
</pre><p>You can include as many templates in a document as you wish with different IDs. When you want to use the template, get the HTML inside the script tag using <code>innerHTML</code>, and pass it as a template. Our first example will change to the following code.</p><pre class="brush: jscript; title: ; notranslate">
&lt;script type='text/javascript'&gt;
  var template = document.getElementById('sample_template').innerHTML;
  var output = Mustache.render(template, view);
  document.getElementById('person').innerHTML = output;
&lt;/script&gt;
</pre><p>As you can see, templates are stored separately and used dynamically when required. This method increases the possibility of reusing templates. However, using inline scripts limits the templates&#8217; scope to a single page. If you have multiple pages, you have to define your templates again. So, including templates in an external file will be the ideal solution &#8211; just like with CSS.</p><h3>Templates as External HTML Snippets</h3><p>In this technique we are going to use jQuery to implement templating. jQuery provides a function called <code>load()</code>, which can be used to fetch part of an external document. We are going to use this method to load templates dynamically from our external templates files. The <code>load()</code> function executes scripts instead of returning them, so we cannot create templates inside of script tags as we did in the previous method. The following example shows the external template files we are going to use.</p><pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;template1&quot; &gt;
&lt;h1&gt;{{name}}&lt;/h1&gt;
&lt;/div&gt;
&lt;div id=&quot;template2&quot; &gt;
&lt;div&gt;{{name}}&lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;template3&quot; &gt;
&lt;p&gt;&lt;span&gt;{{name}}&lt;/span&gt;&lt;/p&gt;
&lt;/div&gt;
</pre><p>We have used <code>&lt;div&gt;</code> elements for templates instead of scripts to keep it compatible with jQuery&#8217;s <code>load()</code> function. Here, we have three different templates with three different IDs. Now, let&#8217;s move on to using these templates in your pages.</p><pre class="brush: xml; title: ; notranslate">
&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;title&gt;Mustache.js External Method&lt;/title&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot; &gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;mustache.js&quot; &gt;&lt;/script&gt;
    &lt;script&gt;
      $(document).ready(function(){
        var view = {
          name : &quot;Joe&quot;,
          occupation : &quot;Web Developer&quot;
        };
        $(&quot;#templates&quot;).load(&quot;template.html #template1&quot;,function(){
          var template = document.getElementById('template1').innerHTML;
          var output = Mustache.render(template, view);
          $(&quot;#person&quot;).html(output);
        });
      });
    &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;p id=&quot;person&quot;&gt;&lt;/p&gt;
    &lt;div id=&quot;templates&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre><p>jQuery inserts the returned document into an HTML element instead of assigning it to a variable. So, we need a dummy container to keep the templates. I have used the <code>templates</code> container which is hidden by default. The example above retrieves <code>template1</code>, and loads it.  Then, we can get the template from the dummy container and pass it to mustache for rendering. This is how the external method works. We can also get the data from a server using an AJAX request.</p><h2>Conclusion</h2><p>Template engines and frameworks are important in managing complex systems with dynamically changing presentation views. Mustache.js is one of the best choices for managing templates on the client side. We started this tutorial by explaining why templates are important. Then, we moved onto various techniques of using mustache templates. Now you will be able to choose the method of implementing mustache templates in your projects.</p><p>We have completed exploring various techniques for using mustache templates, but mustache also comes with tags such as variables, sections, functions and partials, which are used to manage complex templates. Discussing the syntax of each tag is beyond the scope of this tutorial. You can find a comprehensive guide to mustache tags on the <a
href="https://github.com/janl/mustache.js" target="_blank">mustache GitHub page</a>.</p><p>Feel free to share your previous experiences in working with mustache.js!</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/creating-html-templates-with-mustachejs/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Headless WebKit and PhantomJS</title><link>http://www.sitepoint.com/headless-webkit-and-phantomjs/</link> <comments>http://www.sitepoint.com/headless-webkit-and-phantomjs/#comments</comments> <pubDate>Sat, 01 Dec 2012 10:00:21 +0000</pubDate> <dc:creator>Colin Ihrig</dc:creator> <category><![CDATA[Intermediate]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[Headless Browser]]></category> <category><![CDATA[PhantomJS]]></category> <guid
isPermaLink="false">http://jspro.com/?p=1332</guid> <description><![CDATA[If you&#8217;re reading this article, you most likely know what a browser is. Now take away the GUI, and you have what&#8217;s called a headless browser. Headless browsers can do all of the same things that normal browsers do, but faster. They&#8217;re great for automating and testing web pages programmatically. There are a number of [...]]]></description> <content:encoded><![CDATA[<p></p><p>If you&#8217;re reading this article, you most likely know what a browser is. Now take away the GUI, and you have what&#8217;s called a <em>headless browser</em>. Headless browsers can do all of the same things that normal browsers do, but faster. They&#8217;re great for automating and testing web pages programmatically. There are a number of headless browsers in existence, and <a
href="http://phantomjs.org/" title="PhantomJS: Headless WebKit with JavaScript API" target="_blank">PhantomJS</a> is the best.<br
/> <span
id="more-63943"></span></p><p>Built on top of <a
href="http://en.wikipedia.org/wiki/WebKit" title="WebKit - Wikipedia" target="_blank">WebKit</a>, the engine behind Chrome and Safari, PhantomJS gives you a ton of browser power, without the heavy GUI. Getting started with PhantomJS is easy &#8211; just <a
href="http://phantomjs.org/download.html" title="PhantomJS: Download and Install" target="_blank">download the executable</a>. Next, create a file named <code>hello.js</code> and add the following lines.</p><pre class="brush: jscript; title: ; notranslate">
console.log(&quot;Hello World!&quot;);
phantom.exit();
</pre><p>To execute the script, run the command shown below. Note, the <code>phantomjs</code> executable must either be in your current directory, or somewhere in your environment&#8217;s <code>PATH</code>. If everything is configured properly, PhantomJS will print <code>Hello World!</code> to the console, and then terminate when <code>phantom.exit()</code> is called.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><pre>
phantomjs hello.js
</pre><h2>Working With Web Pages</h2><p>Once PhantomJS is up and running, you can begin automating the Web. The following example loads the Google home page, and then saves a screenshot to a file. Line 1 creates a new instance of a web page. On line 4, the web page loads <code>google.com</code>. Once the page finishes loading, the <code>onLoadFinished()</code> callback function is executed. The callback receives a single argument, <code>status</code>, which indicates whether the page loaded successfully or not. The URL of the loaded page is available in <code>page.url</code>. This property can be particularly useful when pages contain redirects, and you want to know exactly where you landed. A screenshot is taken on line 8 using the page&#8217;s <code>render()</code> method. <code>render()</code> can create PNG, GIF, JPEG, and PDF files.</p><pre class="brush: jscript; title: ; notranslate">
var page = require(&quot;webpage&quot;).create();
var homePage = &quot;http://www.google.com/&quot;;
page.open(homePage);
page.onLoadFinished = function(status) {
  var url = page.url;
  console.log(&quot;Status:  &quot; + status);
  console.log(&quot;Loaded:  &quot; + url);
  page.render(&quot;google.png&quot;);
  phantom.exit();
};
</pre><h3>Page Settings</h3><p>Page objects have a number of settings which can be customized based on your application&#8217;s needs. For example, if you&#8217;re only interested in downloading source code, you can speed up your application by ignoring image files and turning off JavaScript. The previous example is rewritten below to reflect these changes. The changed settings are shown on lines 3 and 4. Note that any settings changes <strong>must</strong> take place before the call to <code>open()</code>. If you view the screenshot from this example, you will notice that the Google logo image is missing, but the rest of the page is in tact.</p><pre class="brush: jscript; title: ; notranslate">
var page = require(&quot;webpage&quot;).create();
var homePage = &quot;http://www.google.com/&quot;;
page.settings.javascriptEnabled = false;
page.settings.loadImages = false;
page.open(homePage);
page.onLoadFinished = function(status) {
  var url = page.url;
  console.log(&quot;Status:  &quot; + status);
  console.log(&quot;Loaded:  &quot; + url);
  page.render(&quot;google.png&quot;);
  phantom.exit();
};
</pre><h2>Accessing the File System</h2><p>So far, our examples have loaded pages and saved screenshots as image files. While this is undoubtedly cool, many applications would prefer to store the source code to the file system. PhantomJS makes this possible by providing an extensive file system API. The following example uses the <code>FileSystem</code> module to write the <code>google.com</code> source code to a file. First, the <code>FileSystem</code> module is imported on line 2. On line 6, the output file is opened for writing. On line 7, the data is written to file using the <code>write()</code> method. The actual source code is available via the page&#8217;s <code>content</code> property. Finally, the file is closed and PhantomJS is terminated.</p><pre class="brush: jscript; title: ; notranslate">
var page = require(&quot;webpage&quot;).create();
var fs = require(&quot;fs&quot;);
var homePage = &quot;http://www.google.com/&quot;;
page.open(homePage);
page.onLoadFinished = function(status) {
  var file = fs.open(&quot;output.htm&quot;, &quot;w&quot;);
  file.write(page.content);
  file.close();
  phantom.exit();
};
</pre><h2>Executing JavaScript</h2><p>One of the most powerful features of PhantomJS is the ability to interact with a page via JavaScript. This makes it extremely easy to automate tasks such as clicking buttons and submitting forms. Our next example performs a Web search by loading the Google home page, entering a query, and then submitting the search form. The beginning of the example should look familiar. The new stuff begins, on line 8, where we determine which page has been loaded. If this is the home page, the page&#8217;s <code>evaluate()</code> method is called. <code>evaluate()</code> executes the code you provide in the context of the page. This essentially gives you the same power as the page&#8217;s original developer. How cool is that?</p><pre class="brush: jscript; title: ; notranslate">
var page = require(&quot;webpage&quot;).create();
var homePage = &quot;http://www.google.com/&quot;;
page.open(homePage);
page.onLoadFinished = function(status) {
  var url = page.url;
  console.log(&quot;Status:  &quot; + status);
  console.log(&quot;Loaded:  &quot; + url);
  if (url === homePage) {
    page.evaluate(function() {
      var searchBox = document.querySelector(&quot;.lst&quot;);
      var searchForm = document.querySelector(&quot;form&quot;);
      searchBox.value = &quot;JSPro&quot;;
      searchForm.submit();
    });
  } else {
    page.render(&quot;results.png&quot;);
    phantom.exit();
  }
};
</pre><p>Inside of <code>evaluate()</code>, we locate the search box and form. We set the value of the search box to &#8220;JSPro&#8221;, and then submit the form. This will cause the page&#8217;s <code>onLoadFinished()</code> method to be triggered again. However, this time a screen shot is taken of the search results, and PhantomJS exits.</p><p>PhantomJS also provides two methods, <code>includeJs()</code> and <code>injectJs()</code>, which allow you to add external script files to a page. <code>includeJs()</code> is used to include any script file that is accessible from the page. For example, you can include <a
href="http://jquery.com/" title="jQuery: The Write Less, Do More, JavaScript Library" target="_blank">jQuery</a> in our previous example using the following code. Notice the call to <code>includeJs()</code> on line 9, as well as the jQuery syntax inside of <code>evaluate()</code>.</p><pre class="brush: jscript; title: ; notranslate">
var page = require(&quot;webpage&quot;).create();
var homePage = &quot;http://www.google.com/&quot;;
page.open(homePage);
page.onLoadFinished = function(status) {
  var url = page.url;
  console.log(&quot;Status:  &quot; + status);
  console.log(&quot;Loaded:  &quot; + url);
  if (url === homePage) {
    page.includeJs(&quot;http://code.jquery.com/jquery-1.8.3.min.js&quot;, function() {
      console.log(&quot;Loaded jQuery!&quot;);
      page.evaluate(function() {
        var searchBox = $(&quot;.lst&quot;);
        var searchForm = $(&quot;form&quot;);
        searchBox.val(&quot;JSPro&quot;);
        searchForm.submit();
      });
    });
  } else {
    page.render(&quot;results.png&quot;);
    phantom.exit();
  }
};
</pre><p>The <code>injectJs()</code> method is similar to <code>includeJs()</code>. The difference is that the injected script file does not need to be accessible from the page object. This allows you to, for example, inject scripts from your local file system.</p><h2>PhantomJS and Node.js</h2><p>Sadly, PhantomJS does not integrate particularly well with Node.js. A few projects have been created which try to control PhantomJS from Node.js, but they are all a bit of a kludge. Existing projects use the <a
href="http://nodejs.org/api/child_process.html" title="Child Process Node.js v0.8.15 Manual" target="_blank">child process</a> module to spawn instances of PhantomJS. Next, PhantomJS loads a special web page, which uses <a
href="http://cjihrig.com/blog/how-to-use-websockets/" title="How to Use WebSockets" target="_blank">WebSockets</a> to communicate with Node.js. It might not be ideal, but it works.</p><p>Two of the more popular PhantomJS Node modules are <a
href="https://github.com/alexscheelmeyer/node-phantom" title="alexscheelmeyer/node-phantom" target="_blank">node-phantom</a> and <a
href="https://github.com/sgentle/phantomjs-node" title="sgentle/phantomjs-node" target="_blank">phantomjs-node</a>. I recently started working on my own PhantomJS Node module named <a
href="https://github.com/cjihrig/ghostbuster" title="cjihrig/ghostbuster" target="_blank">ghostbuster</a>. Ghostbuster is similar to node-phantom, but attempts to reduce callback nesting by providing more powerful commands. Making fewer calls to PhantomJS also means less time is wasted communicating over WebSockets. Another alternative is <a
href="https://github.com/assaf/zombie" title="assaf/zombie" target="_blank">zombie.js</a>, a lightweight headless browser built on top of <a
href="https://github.com/tmpvar/jsdom" title="tmpvar/jsdom" target="_blank">jsdom</a>. Zombie isn&#8217;t as powerful as PhantomJS, but it is a true Node.js module.</p><h2>Conclusion</h2><p>After reading this article, you should have a basic grasp on PhantomJS. One of the nicest features about PhantomJS is how simple it is to use. If you&#8217;re already familiar with JavaScript, the learning curve is minimal. PhantomJS also supports a variety of other features that weren&#8217;t covered in this article. As always, I encourage you to check out the <a
href="https://github.com/ariya/phantomjs/wiki/API-Reference" title="API Reference · ariya/phantomjs Wiki" target="_blank">documentation</a>. There are also a number of <a
href="https://github.com/ariya/phantomjs/tree/master/examples" title="phantomjs/examples at master · ariya/phantomjs" target="_blank">examples</a> which show off PhantomJS in all its glory!</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/headless-webkit-and-phantomjs/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Debugging Unit Tests Using js-test-driver</title><link>http://www.sitepoint.com/debugging-unit-tests-using-js-test-driver/</link> <comments>http://www.sitepoint.com/debugging-unit-tests-using-js-test-driver/#comments</comments> <pubDate>Wed, 28 Nov 2012 09:00:25 +0000</pubDate> <dc:creator>Stephen Lum</dc:creator> <category><![CDATA[Advanced]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[debugging]]></category> <category><![CDATA[testing]]></category> <guid
isPermaLink="false">http://jspro.com/?p=926</guid> <description><![CDATA[Unit testing and Test Driven Development (TDD) are common paradigms nowadays. If you are a JavaScript developer, Google has created and open sourced a great tool called js-test-driver to help with unit testing. js-test-driver is a JavaScript unit test runner in the spirit of JUnit, and brings TDD to JavaScript. Unit Testing Overview If you [...]]]></description> <content:encoded><![CDATA[<p></p><p>Unit testing and Test Driven Development (TDD) are common paradigms nowadays. If you are a JavaScript developer, Google has created and open sourced a great tool called <a
href="http://code.google.com/p/js-test-driver/">js-test-driver</a> to help with unit testing. js-test-driver is a JavaScript unit test runner in the spirit of <a
href="http://junit.sourceforge.net/">JUnit</a>, and brings TDD to JavaScript.<br
/> <span
id="more-63937"></span></p><h2>Unit Testing Overview</h2><p>If you have never done any unit testing before, nor entered the world of TDD, you might be asking yourself what the benefits are. There are many detailed discussions on the subject, but I&#8217;ll touch on a few of the more important points.</p><ul><li>Unit tests are useful in regression testing. You can run unit tests after making code changes, and ensure that everything works like it used to. This is especially important in dynamic languages like JavaScript that do not give you compilation errors.</li><li>The more complex/larger the project, the more unit tests will provide you with a return on investment</li><li>A comprehensive suite of unit tests is <em>almost</em> as good as documentation.  With a good suite of unit tests, a developer can open a project and start running/debugging unit tests to better understand the system. This is very helpful when on-boarding a new team member.</li><li><a
href="http://junit.sourceforge.net/">JUnit</a> is a popular Java test framework that was crucial in the development of Test Driven Development. Many of the existing testing frameworks follow the naming conventions and idioms of JUnit.</li></ul><h2>Configuring Your System</h2><p>This tutorial will teach you how to set breakpoints and debug your unit tests from within an Integrated Development Environment (IDE). We will focus on the <a
href="http://www.jetbrains.com/idea/">IntelliJ</a> IDE. This tutorial uses a Microsoft Windows environment, but should work on most operating systems by adjusting the environment variables. You will also need to follow these instructions:</p><ol><li>Download and install IntelliJ. You can download IntelliJ from the <a
href="http://www.jetbrains.com/idea/download/">JetBrains website</a>.</li><li>If you haven&#8217;t done so, download and install the <a
href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">Java Development Kit (JDK)</a>.</li><li>Within IntelliJ, make sure you have installed the js-test-driver plugin. If you do not know how to do this, please refer to the <a
href="http://www.jetbrains.com/idea/webhelp/updating-installing-and-uninstalling-plugins-from-a-repository.html">JetBrains instructions for installing plugins</a>.</li><li>Download the latest <a
href="http://code.google.com/p/js-test-driver/downloads">js-test-driver.jar</a>. At the time of writing, the latest version is 1.3.5. For the purposes of this tutorial, save the jar to <code>C:\devtools\web\js\js-test-driver\1.3.5\js-test-driver-1.3.5.jar</code>.</li><li>Add the following environment variables so that the Java runtime can be invoked from the command line.<pre>
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_7 (or the location of your java install)
PATH=%JAVA_HOME%\bin;%PATH%
</pre><p>You can verify the installation by opening a command prompt and typing <code>java</code>. If Java is installed correctly, you should see output similar to that shown in the screenshot below.</p><p>[image src="http://jspro.com/files/2012/11/js-test-driver-cmd-java.png"]</li><li>Create a new project in IntelliJ by going to the top menu and clicking <code>File | New Project</code>. I have created an IntelliJ project with a Web Module at <code>C:\projects\js-test-driver</code>. The IntelliJ settings are shown in the figure below.<p>[image src="http://jspro.com/files/2012/11/js-test-driver-createproject.png"]</li><li>In TDD and unit testing, it is always a good idea to have a clean, concise separation between your production code and your test code. Create the directories <code>src</code> and <code>test</code> in the IntelliJ project root. After creating these directories, your project should look like the following screenshot.<p>[image src="http://jspro.com/files/2012/11/js-test-driver-srctestdirs.png"]</li></ol><h2>Getting Started</h2><ol><li>We are going to add the &#8220;greeter&#8221; examples that are part of the js-test-driver project. Create a new JavaScript file named <code>greeter.js</code> under the <code>src</code> directory and add the following code.<pre class="brush: jscript; title: ; notranslate">
myapp = {};
myapp.Greeter = function() {};
myapp.Greeter.prototype.greet = function(name) {
  return &quot;Hello &quot; + name + &quot;!&quot;;
};
</pre></li><li>Now we will create the unit test. Create the corresponding JavaScript test file <code>greetertest.js</code> under the <code>test</code> directory, and add the following code.<pre class="brush: jscript; title: ; notranslate">
TestCase(&quot;GreeterTest&quot;, {
  setUp:function () {
  },
  &quot;test greet&quot;: function() {
    var greeter = new myapp.Greeter();
    assertEquals(&quot;Hello World!&quot;, greeter.greet(&quot;World&quot;));
  },
  &quot;test greet null&quot;: function() {
    var greeter = new myapp.Greeter();
    assertNull(greeter.greet(null));
  }
});
</pre></li><li>In <code>greetertest.js</code>, IntelliJ will not understand the <code>TestCase</code> class, and will highlight it in red. Click <code>TestCase</code> and you will be prompted for the JetBrains suggested intention. Next, click <code>Add JsTestDriver assertion framework support</code>, as shown in the following figure. Doing this will add IntelliJ IDE support for js-test-driver.<p>[image src="http://jspro.com/files/2012/11/js-test-driver-assertframework.png"]</li><li>Create a file named <code>js-test-driver.conf</code> in the root of your project. For the purposes of this tutorial, the full path would be <code>C:\projects\js-test-driver\js-test-driver.conf</code>. Add the information shown in the following image to <code>js-test-driver.conf</code>.<p>[image src="http://jspro.com/files/2012/11/js-test-driver-jstestdriver.conf_.png"]</li><li>Now let&#8217;s setup our project for debugging with a breakpoint. Set a breakpoint in the file <code>greetertest.js</code> within the <code>testgreet()</code> function. You can set a breakpoint in IntelliJ by clicking in the left hand margin.</li><li>Create a new IntelliJ Run/Debug configuration of type <code>JavaScript Debug | JavaScript</code> as shown below.<p>[image src="http://jspro.com/files/2012/11/js-test-driver-debug-javascript-remote.png"]</li><li>Change the following values:<ul><li>URL to open: <code>http://localhost:9876/capture</code></li><li>Expand the directory <code>test</code> and enter <code>http://localhost:9876/test/test</code> for Remote URL</li></ul></li><li>As we have seen so far, IntelliJ provides excellent js-test-driver integration. To start the js-test-driver server from directly within IntelliJ, expand the <code>JsTestDriver Server</code> menu item and click the green play button, as shown below.<p>[image src="http://jspro.com/files/2012/11/js-test-driver-server-start.png"]</li><li>Now let&#8217;s debug our JavaScript from within IntelliJ! Start the Debug Configuration we created earlier called <code>JavascriptRemote</code>. You can do so by selecting <code>Run | Debug</code> from the menu. A new browser window will open with the js-test-driver remote console runner loaded as shown below.<p>[image src="http://jspro.com/files/2012/11/js-test-driver-browser-remote-debug.png"]</li><li>Next, open a new command prompt. <code>cd</code> to the root of the IntelliJ project. For the purposes of this project that directory is <code>C:\projects\js-test-driver</code>. Enter the following command:<pre>java -jar C:\devtools\web\js\js-test-driver\1.3.5\js-test-driver-1.3.5.jar --tests all</pre></li><li>After a few moments, IntelliJ should be suspended at the breakpoint we set earlier. Local variables, watch expressions, and other debug goodness will now be available to us. Note: in IntelliJ, intelligent code completion is available in watch expressions!<p>[image src="http://jspro.com/files/2012/11/js-test-driver-breakpoint-suspended.png"]</li></ol><h2>Conclusion</h2><p>This article has taught you to debug JavaScript unit tests with js-test-driver. You should now be able to set breakpoints from within the IntelliJ development environment. Ultimately I hope this will help you produce well tested software for your current and future projects.</p><ul><li>Download the <a
href="https://github.com/jsprodotcom/source/blob/master/debugging-unit-tests-using-js-test-driver.zip" title="Debugging Unit Tests Using js-test-driver Source Code">source code</a> for the examples in this article!</li></ul><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/debugging-unit-tests-using-js-test-driver/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Getting Started with MooTools</title><link>http://www.sitepoint.com/getting-started-with-mootools/</link> <comments>http://www.sitepoint.com/getting-started-with-mootools/#comments</comments> <pubDate>Mon, 29 Oct 2012 06:00:50 +0000</pubDate> <dc:creator>Avinash Zala</dc:creator> <category><![CDATA[Beginner]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[MooTools]]></category> <guid
isPermaLink="false">http://jspro.com/?p=727</guid> <description><![CDATA[This tutorial introduces one of the most popular JavaScript frameworks today, MooTools. MooTools, which stands for My Object Oriented Tools, is compatible with Internet Explorer 6+, Firefox, Opera and Chrome. MooTools is designed to be compact, modular, and of course, object oriented. MooTools is designed for intermediate to expert JavaScript programmers, so make sure you [...]]]></description> <content:encoded><![CDATA[<p></p><p>This tutorial introduces one of the most popular JavaScript frameworks today, MooTools. MooTools, which stands for <em>My Object Oriented Tools</em>, is compatible with Internet Explorer 6+, Firefox, Opera and Chrome. MooTools is designed to be compact, modular, and of course, object oriented. MooTools is designed for intermediate to expert JavaScript programmers, so make sure you have enough experience before diving in.<br
/> <span
id="more-63922"></span></p><h2>Getting MooTools</h2><p>Getting MooTools is fairly simple. MooTools comes in two parts, known as Core and More. Core contains the core classes and modules of the framework, while More contains the additional classes which can be included based on an application&#8217;s needs. MooTools has powerful builder pages which can <a
href="http://mootools.net/core/" title="MooTools - MooTools Core 1.4.5 Builder" target="_blank">customize Core</a> and <a
href="http://mootools.net/more/" title="MooTools - MooTools More 1.4.0.1 Builder" target="_blank">More</a> based on our needs. The current stable version (at the time of writing this article) of MooTools Core is 1.4.5 and More is 1.4.0.1.</p><h2>Element Selectors</h2><p>One of the most basic operations of any JavaScript framework is the selection of elements. MooTools uses <a
href="https://github.com/mootools/slick" title="mootools/slick" target="_blank">Slick</a> as its selector engine. MooTools supports many different types of selectors. This section covers some of the most useful and important selectors.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><h3>Selecting an Element by ID</h3><p>If we want to select an element by ID in plain JavaScript, we need to use the long <code>document.getElementById('id_of_element')</code> syntax. MooTools, like many other JavaScript frameworks, shortens this by using <code>$</code> to select elements. Your code ends up looking like this:</p><pre class="brush: jscript; title: ; notranslate">
var element =  $('id_of_element');
</pre><p>This will create problems if you include MooTools and other libraries that use <code>$</code> (e.g. jQuery) on the same page. To overcome this situation MooTools has provided <code>document.id()</code> as another way to select elements. Your code to select elements by <code>id</code> now looks like this:</p><pre class="brush: jscript; title: ; notranslate">
var element =  document.id('id_of_element');
</pre><h3>Selecting Elements by Class</h3><p>This will return an array of elements of a certain class. To get each individual element, we need to traverse the array, as shown below.</p><pre class="brush: jscript; title: ; notranslate">
$$('.class_name').each(function(ele){
  console.log(ele);
});
</pre><h3>Selecting Elements by Attribute Patterns</h3><p>The following examples select elements whose <code>id</code> and <code>class</code> attributes begin with a certain pattern.</p><pre class="brush: jscript; title: ; notranslate">
$$('[id^=id_start_]').each(function(ele){
  console.log(ele);
});
$$('[class^=class_start_]').each(function(ele){
  console.log(ele);
});
</pre><p>Similarly, the following examples match elements whose <code>id</code> and <code>class</code> attributes end with a certain pattern.</p><pre class="brush: jscript; title: ; notranslate">
$$('[id$=_end_id]').each(function(ele){
  console.log(ele);
});
$$('[class$=_end_class]').each(function(ele){
  console.log(ele);
});
</pre><h2>The DomReady Event</h2><p>DomReady is an event which can only be bound to the window object. DomReady executes as soon as the DOM is loaded, which can be much earlier than the <code>window.load</code> event, which waits for all other resources to load. I suggest reading this <a
href="http://www.xpertdeveloper.com/2010/09/mootools-domready-vs-window-onload/" title="Mootools domready vs window.onload" target="_blank">in depth comparison of DomReady and <code>window.load</code></a>. The following example uses DomReady to wait until the DOM loads before querying it.</p><pre class="brush: jscript; title: ; notranslate">
window.addEvent('domready', function(){
  if(document.id('id_of_element'))
  {
    alert('Element Exists');
  }
});
</pre><h2>Element Creation</h2><p>MooTools can create new HTML elements and inject them into the DOM. Creating a new HTML element in MooTools is very simple. For example, the following code creates a new <code>div</code> element.</p><pre class="brush: jscript; title: ; notranslate">
var new_div = new Element('div', {'class': 'new_div'});
</pre><p>The previous code creates a new element, but does not inject it into the DOM. To perform the injection, you need to call the <code>adopt()</code> method. The following example shows how this is done.</p><pre class="brush: jscript; title: ; notranslate">
var new_div = new Element('div', {'class': 'new_div'});
$$('body').adopt(new_div);
</pre><p>When this code gets executed, you can see the new <code>div</code> added just before the closing <code>body</code> tag.</p><h2>Event Binding</h2><p>Event binding causes code to be executed when certain events are performed on an element. Click, double click, and hovering are examples of common events. You can also create your own custom events, but that is beyond the scope of this article. As an example of MooTools event binding, the following code adds a simple click event handler to an element.</p><pre class="brush: jscript; title: ; notranslate">
document.id('id_of_ele').addEvent('click', function(){
  console.log('I was just clicked');
});
</pre><p>You can also add events to dynamically created elements. The following code adds a click handler to a dynamically created element.</p><pre class="brush: jscript; title: ; notranslate">
var new_div = new Element('div', {'class': 'new_div'});
$$('body').adopt(new_div);
new_div.addEvent('click', function(){
  console.log('I was just clicked');
});
</pre><h2>Browser Detection</h2><p>Last, but not least, is browser detection with MooTools. This is required when you want to write conditional code based on the user’s browser. MooTools provides the <code>Browser</code> object, which gets populated on page load. The following example uses a <code>switch</code> statement to identify the current browser.</p><pre class="brush: jscript; title: ; notranslate">
switch(Browser.name)
{
  case &quot;safari&quot;:
    console.log('I am Safari');
    break;
  case &quot;chrome&quot;:
    console.log('I am Chrome');
    break;
  case &quot;firefox&quot;:
    console.log('I am FireFox');
    break;
  case &quot;opera&quot;:
    console.log('I am Opera');
    break;
  case &quot;ie&quot;:
    console.log('I am IE');
    break;
}
</pre><h2>Conclusion</h2><p>This article has covered a lot of the MooTools basics. There are some great resources out there for learning to use MooTools effectively. I have learned a lot from the <a
href="http://mootools.net/docs/core" title="MooTools Docs - /Intro" target="_blank">MooTools Docs</a> and <a
href="http://davidwalsh.name/" title="David Walsh - MooTools, Dojo Consultant" target="_blank">The David Walsh Blog</a>. You can also refer to <a
href="http://www.xpertdeveloper.com/" title="Expert PHP Developer" target="_blank">my MooTools work</a>.</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/getting-started-with-mootools/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Become a Modernizr Master with Learnable and Ryan Seddon</title><link>http://www.sitepoint.com/master-modernizr-at-learnable/</link> <comments>http://www.sitepoint.com/master-modernizr-at-learnable/#comments</comments> <pubDate>Thu, 11 Oct 2012 05:41:43 +0000</pubDate> <dc:creator>Tom Museth</dc:creator> <category><![CDATA[Beginner]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[modernizr]]></category> <guid
isPermaLink="false">http://jspro.com/?p=494</guid> <description><![CDATA[Interested in learning more about Modernizr? Check out what&#8217;s happening this month over at Learnable, the web&#8217;s premier online learning destination, and part of the SitePoint network. They&#8217;ll be hosting a &#8220;live&#8221; course, where instructor Ryan Seddon and Learnable&#8217;s in-house team of experts will be standing by to answer your questions in a Q&#38;A session. [...]]]></description> <content:encoded><![CDATA[<p></p><p>Interested in learning more about Modernizr? Check out what&#8217;s happening this month over at Learnable, the web&#8217;s premier online learning destination, and part of the SitePoint network. They&#8217;ll be hosting a &#8220;live&#8221; course, where instructor Ryan Seddon and Learnable&#8217;s in-house team of experts will be standing by to answer your questions in a Q&amp;A session. As a member, there&#8217;s no cost to participate.<span
id="more-63910"></span></p><h2>Learn Modernizr</h2><p><a
href="https://learnable.com/courses/modernizr-front-end-development-done-right-2561?v=4" class="button">Getting Started with Modernizr with Ryan Seddon</a><br
/> Starts: 10am Pacific Daylight Time, October 16, 2012</p><p>Modernizr makes it easy for you to write conditional JavaScript and CSS to handle any situation, whether a browser supports a particular feature you wish to implement or not. It’s perfect for tackling progressive enhancement easily.</p><p>If you&#8217;re a front-end whiz (or want to be) and you haven&#8217;t used this tool yet, this is the course for you.</p><p>Happy learning!</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/master-modernizr-at-learnable/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Using JSLint to Refine Your Code</title><link>http://www.sitepoint.com/using-jslint-to-refine-your-code/</link> <comments>http://www.sitepoint.com/using-jslint-to-refine-your-code/#comments</comments> <pubDate>Wed, 10 Oct 2012 06:00:55 +0000</pubDate> <dc:creator>Chee How Chua</dc:creator> <category><![CDATA[Beginner]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Tools and Libraries]]></category> <category><![CDATA[resources]]></category> <guid
isPermaLink="false">http://www.sitepoint.com/jspro/?p=91</guid> <description><![CDATA[JavaScript is an increasingly popular language thanks to the proliferation of web apps and the adoption of HTML5. Part of JavaScript&#8217;s appeal is the ease by which one can begin writing useful and fun stuff with it. There&#8217;s no need for heavyweight integrated development environments (IDEs) or third-party apps. Just open any text editor, save [...]]]></description> <content:encoded><![CDATA[<p></p><p>JavaScript is an increasingly popular language thanks to the proliferation of web apps and the adoption of HTML5. Part of JavaScript&#8217;s appeal is the ease by which one can begin writing useful and fun stuff with it. There&#8217;s no need for heavyweight integrated development environments (IDEs) or third-party apps. Just open any text editor, save the file, and open it in a web browser.<span
id="more-63900"></span></p><p>JavaScript&#8217;s lure can easily turn into a trap for novice programmers. The malleability of the language can create monstrous bugs in sophisticated scripts. For example, a missing local variable declaration can mysteriously manifest itself elsewhere on the page by altering global variables.</p><p>[image src="http://jspro.com/files/2012/10/jslint1.png" href="http://jspro.com/files/2012/10/jslint1.png"]</p><p>Enter <a
href="http://jslint.com/">JSLint</a>. According to its website, JSLint is a &#8220;JavaScript Code Quality Tool.&#8221; Its author, Douglas Crockford, is well known for his work on the development of JavaScript (also known as ECMAScript) and JSON. JSLint helps JavaScript programmers by making sure certain coding conventions are followed. JSLint is based on the premise of strict mode, which is available in the fifth edition of the ECMAScript standard. With strict mode, you are making your code run with a set of more restrictive rules than normal.<div
id='div-gpt-ad-1328644474660-10' style='width:728px; height:90px;'> <script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1328644474660-10'); });</script> </div></p><h2>Using JSLint</h2><p>Let’s run through an example usage of JSLint. We are writing a simple jQuery plugin that displays a message specified in the <code>msg</code> parameter with a prefix. The prefix is hidden if we pass the value <code>false</code> through the <code>type</code> parameter.</p><pre class="brush: jscript; title: ; notranslate">(function ($) {
    $.fn.loading = function(msg, type, cssClass){
        var prefixes = {
            warning: 'Warning: ' + msg,
            error: 'Error: ' + msg,
            info: 'Info: ' + msg,
            warning: 'Caution: ' + msg,
        };
        if (type) {
            concatMsg = prefixes[type];
        } else {
            concatMsg = msg;
        }
        $(this).each(function()  {
            var tis = $(this)
            if (msg == false) {
                tis.html('');
            } else {
                tis.html(concatMsg);
            }
        });
     }
})(jQuery);</pre><p>Although this piece of code works fine as a plugin for jQuery, when you use it in Firefox or Chrome, you can see that there are some glaring mistakes and some very subtle ones. Instead of spending your mental energy digging out the problems, let&#8217;s use JSLint to help us. Copy the function code into the text area on the JSLint site and click the &#8220;JSLint&#8221; button. Some of the resulting JSLint output is shown in the figure below.</p><p>[image src="http://jspro.com/files/2012/10/jslint2.png" href="http://jspro.com/files/2012/10/jslint2.png"]</p><p>The first error pointed out by JSLint is that the <code>"use strict"</code> statement is missing. This error indicates that the function is not executed in strict mode. To correct this error, enable strict mode by adding the following string literal to the beginning of the function body.</p><pre class="brush: jscript; title: ; notranslate">
    'use strict';
</pre><p>After enabling strict mode, click the &#8220;JSLint&#8221; button again. The reported error of the missing <code>"use strict"</code> should be gone. We can now move on to the next error, shown in the following figure. This error deals with whitespace, and is more cosmetic than functional. Since this is not an actual error, you can safely ignore it.</p><p>[image src="http://jspro.com/files/2012/10/jslint3.png" href="http://jspro.com/files/2012/10/jslint3.png"]</p><p>You can choose to stick with no space after the <code>function</code> keyword, and suppress the error message by scrolling to the bottom of the page and switching the &#8220;messy white space&#8221; option to <code>true</code>. For now, however, we want to keep the default behavior because this option also checks for other whitespace issues as we will see later.</p><p>Also notice that the second and third errors reported by JSLint are also on the same line but at different positions. Looks like a space between the closing parenthesis and the opening brace is also recommended by JSLint, so fix that now.</p><p>By clicking the &#8220;JSLint&#8221; button again, we see that the next problem is on line 8, at position 39. The <code>prefixes</code> object literal contains two identical <code>warning</code> properties, which is obviously a mistake. Let&#8217;s correct the problem by replacing the second occurrence of <code>warning</code> with <code>caution</code>.</p><p>[image src="http://jspro.com/files/2012/10/jslint7.png" href="http://jspro.com/files/2012/10/jslint7.png"]</p><p>Without clicking the &#8220;JSLint&#8221; button again, let&#8217;s look at the next error, shown in the following figure. The object literal contains a trailing comma. Browsers such as Chrome and Firefox may be tolerant of such mistakes but Internet Explorer does not take too kindly to such transgressions. To correct the problem, simply remove the comma.</p><p>[image src="http://jspro.com/files/2012/10/jslint8.png" href="http://jspro.com/files/2012/10/jslint8.png"]</p><p>The next two errors indicate that <code>concatMsg</code> was used before it was defined. When a variable is not defined in the current scope, JavaScript checks the enclosing scopes to see if it was defined elsewhere. If you are using code from a third-party source that happens to define this exact variable in the global scope, it can take you countless, hair-pulling hours to find the bug. Fortunately, with JSLint, we are able to nip the problem in the bud.</p><p>[image src="http://jspro.com/files/2012/10/jslint9.png" href="http://jspro.com/files/2012/10/jslint9.png"]</p><p>While fixing this problem, we can also refactor our code. Since the default value of <code>concatMsg</code> is <code>msg</code>, we can assign this value immediately and change it later if need be. The code for <code>concatMsg</code> can now be rewritten as shown below.</p><pre class="brush: jscript; title: ; notranslate">var concatMsg = msg;
if (type) {
    concatMsg = prefixes[type];
}</pre><p>Next, we encounter the same whitespace issue as earlier, which can be corrected in the same way. Next, JSLint reports that a semicolon is missing. This message is shown below. Without the semicolon, JSLint assumes that the statement is never terminated. That is why it saw <code>if</code> while expecting a semicolon. While the language specification says that the ending semicolon is optional, it is good practice to include it. This is another area where sloppy coding can lead to hard-to-find bugs in large scale productions. By linting our code, we can fix such problems quickly and easily.</p><p>[image src="http://jspro.com/files/2012/10/jslint11.png" href="http://jspro.com/files/2012/10/jslint11.png"]</p><p>The following error is another good one. There are equality and strict equality checks in JavaScript. In our code, by not checking for strict equality the plugin behaves the same if either an empty string or the Boolean value <code>false</code> is specified as the first parameter. To correct the error, use the strict equality operator.</p><p>[image src="http://jspro.com/files/2012/10/jslint12.png" href="http://jspro.com/files/2012/10/jslint12.png"]</p><p>This is a good time for us to click the &#8220;JSLint&#8221; button again. The first error, shown below, is reported at line 10. JSLint seems to think that another best practice for writing JavaScript is to group variable declarations together. Although <code>concatMsg</code> is right after <code>prefixes</code>, JSLint prefers that you group the variable declarations in a single statement, separated by commas.</p><p>[image src="http://jspro.com/files/2012/10/jslint14.png" href="http://jspro.com/files/2012/10/jslint14.png"]</p><p>The next error is another cosmetic suggestion by JSLint. The fact that there is one more space than the expected number is pretty trivial at first glance. However, indentation problems can lead to bugs that are hard to catch in large scripts. For consistency, move the closing brace back into place by removing the extra space.</p><p>[image src="http://jspro.com/files/2012/10/jslint15.png" href="http://jspro.com/files/2012/10/jslint15.png"]</p><p>The next problem reported by JSLint is similar to what we have seen before, but it is manifested in a different form. JavaScript functions can be assigned to variables. As with any other variable assignment, JSLint expects a terminating semicolon.</p><p>[image src="http://jspro.com/files/2012/10/jslint16.png" href="http://jspro.com/files/2012/10/jslint16.png"]</p><p>Finally, two problems are reported at the last line, as shown below. The first problem is a suggestion to place the closing parentheses after the closing one behind jQuery because it leaves no ambiguity that you want the function definition to be a closure. The second problem is that in JSLint’s view, the variable jQuery is not present, although it might have been included in the web page by linking to a jQuery file. To address this issue, type <code>jQuery</code> into the bottom text field.</p><p>[image src="http://jspro.com/files/2012/10/jslint17.png" href="http://jspro.com/files/2012/10/jslint17.png"]</p><p>If you run JSLint again, it will detect that the function accepts three parameters. However, in this example, the third parameter is never used. There are two approaches you can take here. The first one is to remove the parameter since it is never used. The second option is to toggle the JSLint property “unused parameters” to <code>true</code>, as shown below. Choose this option only if you really want to keep the parameter in the function signature for some reason.</p><p>[image src="http://jspro.com/files/2012/10/jslint19.png" href="http://jspro.com/files/2012/10/jslint19.png"]</p><p>After using JSLint to improve our code, the final product is shown below.</p><pre class="brush: jscript; title: ; notranslate">(function ($) {
    'use strict';
    $.fn.loading = function (msg, type, cssClass) {
        var prefixes = {
            warning: 'Warning: ' + msg,
            error: 'Error: ' + msg,
            info: 'Info: ' + msg,
            caution: 'Caution: ' + msg
        }, concatMsg = msg;
        if (type) {
            concatMsg = prefixes[type];
        }
        $(this).each(function () {
            var tis = $(this);
            if (msg === false) {
                tis.html('');
            } else {
                tis.html(concatMsg);
            }
        });
    };
}(jQuery));</pre><h2>JSLint Directives</h2><p>JSLint directives allow you to define variables and provide other options to JSLint from directly within the source code. This frees you from having to set the JSLint GUI options repeatedly. For example, the comments in the following example define a global variable named <code>jQuery</code> and set the &#8220;unparam&#8221; option to <code>true</code>.</p><pre class="brush: jscript; title: ; notranslate">/*global jQuery*/
/*jslint unparam: true */
(function ($) {
    ‘use strict’;
…
}(jQuery));</pre><h2>Conclusion</h2><p>In this short example, JSLint has pointed out some critical errors and some seemingly insignificant ones. The fact that JSLint helps us catch these issues before we actually run the code is hugely beneficial in terms of developer productivity and application quality. If you are serious about writing production quality code, always run it through JSLint before pushing it to the server. JSLint is even contained in a single JS file, so you can download it use it offline too!</p><div
class='after-content-widget-1'><div
id="sitepointcontextualcontentmanagerwidget-5" class="widget widget_sitepointcontextualcontentmanagerwidget"><div
class="dfp-ad show-desktop"><div
id="div-gpt-ad-1340873946991-4" style="width: 728px; height: 90px;"> <script type="text/javascript">googletag.cmd.push(function() { googletag.display("div-gpt-ad-1340873946991-4"); });</script> </div></div></div></div>]]></content:encoded> <wfw:commentRss>http://www.sitepoint.com/using-jslint-to-refine-your-code/feed/</wfw:commentRss> <slash:comments>7</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using memcached
Database Caching 52/94 queries in 0.442 seconds using memcached
Object Caching 2190/2415 objects using memcached

Served from: www.sitepoint.com @ 2013-05-13 15:05:46 --