O:9:"MagpieRSS":23:{s:6:"parser";i:0;s:12:"current_item";a:0:{}s:5:"items";a:10:{i:0;a:13:{s:5:"title";s:26:"Getting Started with Parse";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/E_IivGJ37A4/";s:8:"comments";s:86:"http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-parse/#comments";s:7:"pubdate";s:31:"Tue, 13 Nov 2012 17:00:25 +0000";s:2:"dc";a:1:{s:7:"creator";s:10:"Tilo Mitra";}s:8:"category";s:52:"DatabasesJavaScript & AJAXTutorialscloudparsestorage";s:4:"guid";s:32:"http://net.tutsplus.com/?p=28000";s:11:"description";s:22215:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28000&c=1011357104' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28000&c=1011357104' border='0' alt='' /></a><p>I am a big fan of <a
href="https://www.parse.com/">Parse</a>, a technology that makes developing web and mobile apps faster. It lets you store, sync and push data in the cloud without writing a line of server-side code. Read on to see how you can integrate Parse in your next project.</p><p><span
id="more-28000"></span></p><hr
/><h2>A Bit of Background</h2><blockquote
class="pullquote"><p>Interacting with the database is extremely painless!</p></blockquote><p>Let&#8217;s take a step back and evaluate where web development was five years ago. We were using languages such as PHP/Ruby on the back-end that interacted with relational databases (such as MySQL), and our front-end was littered with various JavaScript files. I don&#8217;t know about you, but most of my projects were on some server with a small amount of disk space, RAM and bandwidth.</p><p>A lot of new technologies leverage the cloud, and it&#8217;s not uncommon to see developers taking advantage of these cost-effective services, such as AWS, Amazon S3, Heroku, and more. The introduction of these services essentially altered the web development landscape; more of what we do resides in the cloud.</p><p>Today, we&#8217;re going to look at Parse, a startup that offers a cloud-based data management system. By leveraging their service, I was able to rapidly create new mobile and web apps. We&#8217;re going to use Parse to create the obligatory To-do web application, and I hope it gives you a taste of what the service can offer.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2152_parse/app-screenshot.png" alt="Envato Todo List App"></div><hr
/><h2>What&#8217;s Parse?</h2><p>Simply put, Parse is a cloud-based data management system that allows you to quickly develop web and mobile apps.</p><blockquote><p>It makes developing apps <em>really</em> easy by taking the back-end out of your hands.</p></blockquote><p>So, how&#8217;s this work? Well, let&#8217;s assume you&#8217;re a web developer. You can add the Parse JavaScript file on your page, get an API key, and start saving &#8220;objects&#8221; in the cloud with only a few lines of code. Parse frees you from setting up a server-side stack.</p><p>Think about this for a minute. Traditionally, you set up a server-side stack (LAMP, or RoR, ASP.NET, or something else), set up a database, and then interact with it via Ajax on the client. Parse just reduced all that work to a few lines of code.</p><p>In this tutorial, we&#8217;ll use Parse&#8217;s JavaScript SDK. You&#8217;re not limited to using only JavaScript, however; there are Parse libraries in many different languages, including PHP, NodeJS, Java, C# and more. You can find all the available libraries <a
href="https://parse.com/docs/api_libraries">here</a>.</p><hr
/><h2>Using Parse for Your Web-based Projects</h2><p>Before we start, let&#8217;s take a minute and think how a traditional To-do list app could be created using a LAMP stack.</p><ul><li>You would create a MySQL database.</li><li>You may have a PHP class that is responsible for performing CRUD operations. Optionally, you could just have a bunch of PHP functions.</li><li>You may use JavaScript and Ajax on the client-side to call the respective PHP scripts and pass in query strings.</li><li>You would need to sanitize the input to protect against XSS attacks, as well as worry about database security in general.</li><li>If a collaborative app, you would need to track different users and manage their lists. More code, more tables, and more schemas.</li><li>You would need to make sure your database stays performant.</li></ul><p>You get the idea. There&#8217;s a lot to think about and many areas to make mistakes. Parse handles these issues for us.</p><h3>Create a Parse Account</h3><p>Before you do anything, create a <a
href="https://parse.com/">free Parse account</a>. Then create a new app called EnvatoTodo.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2152_parse/create-new-app.png" alt="Create a new Parse App"></div><h3>Download the Empty Project</h3><p>Parse provides a great QuickStart guide to help you get started. Select JavaScript and choose EnvatoTodo from the drop down menu in step 2 (shown in the image below). Parse will generate a zip file that contains the Parse SDK and <code>index.html</code>.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2152_parse/quickstart.png" alt="Parse Quickstart Guide"></div><h3>The Client-Side</h3><p>Before we start interacting with Parse, let&#8217;s set up a basic client-side structure for our application. Since the UI is not the focus of this application, I&#8217;ll just show you the code that I used. It&#8217;s nothing fancy, but I&#8217;m using YUI3. You could optionally use jQuery. Everything is in <code>index.html</code>.</p><pre class="brush: xml; title: ; notranslate">&lt;!DOCTYPE html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;title&gt;Todo App Built on Parse&lt;/title&gt;
  &lt;meta name=&quot;description&quot; content=&quot;My Parse App&quot;&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;css/reset.css&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;css/styles.css&quot;&gt;
  &lt;script src=&quot;http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;http://www.parsecdn.com/js/parse-1.0.19.min.js&quot;&gt;&lt;/script&gt;
    &lt;style&gt;
        body {
            font-family: &quot;HelveticaNeue-Light&quot;, sans-serif;
            font-weight:300;
        }
        h2 {
            font-size:16px;
            text-transform:uppercase;
        }
        a {
            text-decoration:none;
        }
        .hidden {
            display:none;
        }
        #main {
            text-align:center;
        }
        input {
            padding: 10px;
            border-radius: 3px;
            border:1px solid #ccc;
            box-shadow: inset 0 0 10px #eee;
            font-size:24px;
        }
        #input-wrapper {
            padding-bottom:15px;
        }
        #list-item-submit {
            background: #73D175;
            color: white;
            box-shadow:none;
            border-color: #599E5A;
        }
        li {
            text-align:left;
            font-family:sans-serif;
            list-style: none;
            padding: 10px 0;
            border-bottom:1px solid #ccc;
            margin-left:-10px;
        }
        li input {
            margin-right:15px;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Todo List built on &lt;a href=&quot;http://www.parse.com&quot; alt=&quot;Parse&quot;&gt;Parse&lt;/a&gt;&lt;/h1&gt;
  &lt;div id=&quot;main&quot;&gt;
        &lt;div id=&quot;input-wrapper&quot;&gt;
            &lt;input type=&quot;text&quot; id=&quot;list-input&quot; placeholder=&quot;Enter a todo here...&quot;&gt;
            &lt;input type=&quot;button&quot; id=&quot;list-item-submit&quot; value=&quot;Add&quot;&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;h2&gt;Incomplete Tasks&lt;/h2&gt;
            &lt;ul id=&quot;incomplete-items&quot;&gt;
                &lt;li id=&quot;no-incomplete-message&quot;&gt;There are no incomplete tasks! Consider adding one above.&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
  &lt;/div&gt;
    &lt;!-- This is a template that we'll be using to populate our list items --&gt;
    &lt;script id=&quot;todo-items-template&quot; type=&quot;x/handlebars&quot;&gt;
        &lt;li class=&quot;list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;{id}&quot;&gt;{content}&lt;/li&gt;
    &lt;/script&gt;
    &lt;script&gt;
        //Use the YUI 'node' module.
        YUI().use('node', function(Y) {
            //Lets declare some variables that we'll be using.
            var ListItem,
            query,
            noTasksMessage = Y.one('#no-incomplete-message'),
            submitBtn = Y.one(&quot;#list-item-submit&quot;),
            incompleteItemList = Y.one('#incomplete-items'),
            completeItemList = Y.one('#complete-items'),
            input = Y.one(&quot;#list-input&quot;);
            //The rest of our application code will go below.
            submitBtn.on('click', function(e) {
                /*
                When the submit button is clicked, we want to get the contents of the input and save a new todo list item.
                */
            });
            /*
            When a &lt;li&gt; is clicked, we want to save that item as being complete. We use 'delegate' here instead of 'on' so that we only create one event listener instead of one for each checkbox.
            */
            incompleteItemList.delegate('click', function(e) {
            }, 'li');
            /* We also want to get the 10 most recent incomplete tasks and add them to &lt;div id=&quot;incomplete-items&quot;&gt;&lt;/div&gt; */
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>The important thing to note in the above code is the inclusion of the Parse JavaScript file, <code>&lt;script src="http://www.parsecdn.com/js/parse-1.0.19.min.js"&gt;&lt;/script&gt;</code>. This file contains the Parse object that we will interact with.</p><h3>Add Classes in the Data Browser</h3><blockquote
class="pullquote"><p>Parse frees you from setting up a server-side stack.</p></blockquote><p>Let&#8217;s get back to Parse. View the Data Browser for EnvatoTodo (it&#8217;s currently empty). The Data Browser is similar to a MySQL database server, but the Parse DB is schema-less. While you can specify columns in the Data Browser, you can actually save any object with simple JSON (not unlike many NoSQL/Document databases). This is an extremely important and useful feature of Parse.</p><p>We&#8217;re going to go ahead and add a &#8220;class&#8221; to the database. Think of a class as a table. The reason it&#8217;s called a class is because you&#8217;ll generally create objects from a certain class and then save that object to the database.</p><p><strong>Disclaimer:</strong> JavaScript does not officially have classes (yet), but it does have the logical equivalent. For the sake of simplicity, I will use the terminology &#8220;class&#8221; in this tutorial.</p><p>Parse has five types of classes.</p><ul><li><strong>User classes</strong> store user-specific information, and Parse provides sugar methods such as <code>signUp()</code>, <code>login()</code>, and more to help with user administration.</li><li><strong>Installation classes</strong> are typically used to send push notifications for mobile apps. Yes, Parse supports push notifications to all clients.</li><li><strong>Role classes</strong> help segregate users into specific roles, controlling access to read/write to other classes. This is called ACL (access control list) within Parse.</li><li><strong>Product classes</strong> store in-app product data.</li><li><strong>Custom classes</strong> are for anything else.</li></ul><p>Let&#8217;s create a custom class called <code>ListItem</code>. Once it&#8217;s created, you&#8217;ll notice it already has four properties. Parse automatically updates the properties of every class that you create. Some classes, such as user classes, may have their own specific properties.</p><p>Our <code>ListItem</code> objects will contain a <code>content</code> property to show what the Todo contains, and an <code>isComplete</code> property to indicate whether the Todo was completed. We could add columns for these properties, but Parse will figure it out from our JSON.</p><h3>Initializing Parse</h3><p>Let&#8217;s go back to <code>index.html</code> to add some code. The first thing we want to do is initialize Parse with our App ID and JavaScript key. These can be found under the Overview tab of your application inside the Data Browser. Add the following line to your JavaScript, replacing <code>APP_ID</code> and <code>JS_KEY</code> with the appropriate values:</p><pre class="brush: jscript; title: ; notranslate">
Parse.initialize(APP_ID, JS_KEY);
</pre><h3>Saving Todos</h3><p>Let&#8217;s start adding functionality to our application. We&#8217;ll first save a To-do list item when the user clicks the add button. The following code is all we need for this functionality:</p><pre class="brush: jscript; title: ; notranslate">
submitBtn.on('click', function(e) {
    //Extend the native Parse.Object class.
    var ListItem = Parse.Object.extend(&quot;ListItem&quot;);
    //Instantiate an object of the ListItem class
    var listItem = new ListItem();
    //listItem is now the object that we want to save, so we assign the properties that we want on it.
    listItem.set(&quot;content&quot;, text);
    listItem.set(&quot;isComplete&quot;, false);
    //We call the save method, and pass in success and failure callback functions.
    listItem.save(null, {
        success: function(item) {
        //Success Callback
    },
    error: function(gameScore, error) {
        //Failure Callback
    }
    });
});
</pre><p>Interacting with the database is extremely painless! Every custom class in Parse inherits from <code>Parse.Object</code>; therefore, <code>ListItem</code> is a subclass. The string argument <code>"ListItem"</code> tells Parse that this class correlates to the ListItem table that we created. Then we create a new <code>ListItem</code> object, set its properties, and call <code>save()</code>.</p><h3>Showing Items</h3><p>In order to display a list of To-do items, we&#8217;ll use the <a
href="https://parse.com/docs/js_guide">Parse JavaScript API</a> to query the ten most recently saved items, and list those below the app. This will give you an idea as to how queries work in Parse.</p><pre class="brush: jscript; title: ; notranslate">
//Once again, we extend the Parse.Object class to make the ListItem class
ListItem = Parse.Object.extend(&quot;ListItem&quot;);
//This time, we use Parse.Query to generate a new query, specifically querying the ListItem table.
query = new Parse.Query(ListItem);
//We set constraints on the query.
query.equalTo('isComplete', false)
query.limit = 10;
query.descending('createdAt');
//We submit the query and pass in callback functions.
query.find({
  success: function(results) {
    //Success callback
  },
  error: function(error) {
    //Error Callback
  }
});
</pre><p>Once again, it&#8217;s fairly simple and easy to read. The <code>Parse.Query()</code> method is quite powerful. Here, we perform a fairly basic query, but Parse queries can be complex as well. You can query for specific regular expressions, perform relational queries, and many more. Be sure to visit the <a
href="https://parse.com/docs/js_guide#queries">Query Documentation</a> for more examples and code snippets.</p><h3>Putting it all together</h3><p>The next thing we need to add is the ability to mark a to-do item as complete when checking the item&#8217;s checkbox. Each checkbox has a unique <code>id</code> associated with the Parse object that it represents. Therefore, when a checkbox is clicked, we need to:</p><ul><li>Get the id.</li><li>Query for a Parse object with that id.</li><li>Get the returned Parse object, and update it&#8217;s <code>isComplete</code> property as <code>true</code>.</li><li>Save the updated object.</li><li>Remove it from the displayed list.</li></ul><p>Here&#8217;s what that code looks like:</p><pre class="brush: jscript; title: ; notranslate">
incompleteItemList.delegate('click', function (e) {
    //keep a reference to this
    var self = this;
    //create a Parse query object
    var query = new Parse.Query(ListItem);
    //The query.get() method requires the objectId as its first argument. It returns the object with that id.
    query.get(self.one('input').get('id'), {
      success: function(item) {
        //Once the object is returned, we update its property and save it.
        item.set('isComplete', true);
            item.save();
            //Since the item is no longer incomplete, we remove it from the list.
            self.remove();
            //If there's nothing in the list, show a message saying the list is empty.
            if (incompleteItemList.all('li').size() &gt;= 1) {
                noTasksMessage.removeClass('hidden');
            }
      },
      error: function(object, error) {
            alert(&quot;Error when updating todo item: &quot; + error.code + &quot; &quot; + error.message);
      }
    });
}, 'li');
</pre><p>In this snippet, we query for an individual element with a specific <code>id</code>, update it, and save it. Then we remove it from the list with <code>self.remove()</code>.</p><p>In Parse, updating objects is very similar to saving objects&#8211;we call <code>save()</code> in both cases. Parse figures out whether it&#8217;s an existing (dirty) object, or an entirely new object and performs the appropriate action.</p><h3>Complete Source Code</h3><p>With that, we&#8217;re good to go! Pretty easy, eh? Download the attached ZIP file and open <code>index.html</code> to view the entire source code.</p><hr
/><h2>Other Features</h2><p>In this tutorial, we primarily looked at Parse from a web development point-of-view. However, the service was originally started with mobile developers in mind. Parse has a very thorough SDK for Android and iOS, and it supports features such as push notifications to all users of your mobile app.</p><blockquote><p>Some other big features that we didn&#8217;t cover in this tutorial involve users, roles, and storing relational information.</p></blockquote><p>Parse makes it relatively simple to create users, and assign different roles to them. For example, in a learning management system, you may have &#8220;Teachers&#8221;, &#8220;Students&#8221;, and &#8220;Administrators&#8221;. By assigning roles, you can specify which type of user has access to certain Parse objects.</p><hr
/><h2>What about Security?</h2><blockquote
class="pullquote"><p>A lot of new technologies leverage the cloud&#8230;</p></blockquote><p>As a developer, I like that Parse takes care of a lot of the security concerns that I have. As it states on the website, the Parse SDKs are designed &#8220;so that you typically don&#8217;t need to worry about how data is saved.&#8221; There&#8217;s still the issue of users having access to information that they shouldn&#8217;t be able to. To address this concern, Parse offers Object-level and Class-level permissions.</p><p>Object-level permissions allow a developer to specify an array of object IDs that have access to read and/or write the object. Class-level permissions allow a developer to specify what aspects of a Parse class can be manipulated from the API. The following operations can be allowed or denied on a per-class basis: Get, Find, Update, Create, Delete, and Add Fields.</p><hr
/><h2>Pros and Cons</h2><p>I want to stress is that Parse is not suitable for every type of project. Although the free plan is very generous, Parse is a paid service. It can get <a
href="https://parse.com/plans">expensive</a> if you go above certain limits. Luckily, the pricing model is very transparent, and you should be able to figure out how much your app can cost. Generally speaking, I use it for smaller projects where I can anticipate a certain cap when it comes to the number of API requests that I make. I have yet to try Parse for a large project.</p><blockquote><p>One common issue with a service such as Parse is the lock-in effect.</p></blockquote><p>If you use Parse for a small project that suddenly takes off, it can be difficult to move to a difference service or platform. As you can imagine, replacing Parse with your own back-end would entail a significant amount of refactoring. This doesn&#8217;t mean you shouldn&#8217;t use Parse, but it&#8217;s something to keep in mind.</p><hr
/><h2>Concluding Remarks</h2><p>In this tutorial, we looked at how we can use Parse to create a relatively simple web application. I&#8217;ve used this service for a number of projects for various clients, and I find the Parse team to be very helpful when issues arise. I encourage you give the service a try, and make your own decision!</p><p>Disclosure: I have no relationship with Parse or any of its employees. I&#8217;m just a developer who uses their service, and I find it to be a helpful addition to my development workflow.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/0/da"><img src="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/1/da"><img src="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=E_IivGJ37A4:cK2X1Hva7bQ:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=E_IivGJ37A4:cK2X1Hva7bQ:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=E_IivGJ37A4:cK2X1Hva7bQ:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/E_IivGJ37A4" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:82:"http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-parse/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"13";}s:10:"feedburner";a:1:{s:8:"origlink";s:77:"http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-parse/";}s:7:"summary";s:22215:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28000&c=1011357104' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28000&c=1011357104' border='0' alt='' /></a><p>I am a big fan of <a
href="https://www.parse.com/">Parse</a>, a technology that makes developing web and mobile apps faster. It lets you store, sync and push data in the cloud without writing a line of server-side code. Read on to see how you can integrate Parse in your next project.</p><p><span
id="more-28000"></span></p><hr
/><h2>A Bit of Background</h2><blockquote
class="pullquote"><p>Interacting with the database is extremely painless!</p></blockquote><p>Let&#8217;s take a step back and evaluate where web development was five years ago. We were using languages such as PHP/Ruby on the back-end that interacted with relational databases (such as MySQL), and our front-end was littered with various JavaScript files. I don&#8217;t know about you, but most of my projects were on some server with a small amount of disk space, RAM and bandwidth.</p><p>A lot of new technologies leverage the cloud, and it&#8217;s not uncommon to see developers taking advantage of these cost-effective services, such as AWS, Amazon S3, Heroku, and more. The introduction of these services essentially altered the web development landscape; more of what we do resides in the cloud.</p><p>Today, we&#8217;re going to look at Parse, a startup that offers a cloud-based data management system. By leveraging their service, I was able to rapidly create new mobile and web apps. We&#8217;re going to use Parse to create the obligatory To-do web application, and I hope it gives you a taste of what the service can offer.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2152_parse/app-screenshot.png" alt="Envato Todo List App"></div><hr
/><h2>What&#8217;s Parse?</h2><p>Simply put, Parse is a cloud-based data management system that allows you to quickly develop web and mobile apps.</p><blockquote><p>It makes developing apps <em>really</em> easy by taking the back-end out of your hands.</p></blockquote><p>So, how&#8217;s this work? Well, let&#8217;s assume you&#8217;re a web developer. You can add the Parse JavaScript file on your page, get an API key, and start saving &#8220;objects&#8221; in the cloud with only a few lines of code. Parse frees you from setting up a server-side stack.</p><p>Think about this for a minute. Traditionally, you set up a server-side stack (LAMP, or RoR, ASP.NET, or something else), set up a database, and then interact with it via Ajax on the client. Parse just reduced all that work to a few lines of code.</p><p>In this tutorial, we&#8217;ll use Parse&#8217;s JavaScript SDK. You&#8217;re not limited to using only JavaScript, however; there are Parse libraries in many different languages, including PHP, NodeJS, Java, C# and more. You can find all the available libraries <a
href="https://parse.com/docs/api_libraries">here</a>.</p><hr
/><h2>Using Parse for Your Web-based Projects</h2><p>Before we start, let&#8217;s take a minute and think how a traditional To-do list app could be created using a LAMP stack.</p><ul><li>You would create a MySQL database.</li><li>You may have a PHP class that is responsible for performing CRUD operations. Optionally, you could just have a bunch of PHP functions.</li><li>You may use JavaScript and Ajax on the client-side to call the respective PHP scripts and pass in query strings.</li><li>You would need to sanitize the input to protect against XSS attacks, as well as worry about database security in general.</li><li>If a collaborative app, you would need to track different users and manage their lists. More code, more tables, and more schemas.</li><li>You would need to make sure your database stays performant.</li></ul><p>You get the idea. There&#8217;s a lot to think about and many areas to make mistakes. Parse handles these issues for us.</p><h3>Create a Parse Account</h3><p>Before you do anything, create a <a
href="https://parse.com/">free Parse account</a>. Then create a new app called EnvatoTodo.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2152_parse/create-new-app.png" alt="Create a new Parse App"></div><h3>Download the Empty Project</h3><p>Parse provides a great QuickStart guide to help you get started. Select JavaScript and choose EnvatoTodo from the drop down menu in step 2 (shown in the image below). Parse will generate a zip file that contains the Parse SDK and <code>index.html</code>.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2152_parse/quickstart.png" alt="Parse Quickstart Guide"></div><h3>The Client-Side</h3><p>Before we start interacting with Parse, let&#8217;s set up a basic client-side structure for our application. Since the UI is not the focus of this application, I&#8217;ll just show you the code that I used. It&#8217;s nothing fancy, but I&#8217;m using YUI3. You could optionally use jQuery. Everything is in <code>index.html</code>.</p><pre class="brush: xml; title: ; notranslate">&lt;!DOCTYPE html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;title&gt;Todo App Built on Parse&lt;/title&gt;
  &lt;meta name=&quot;description&quot; content=&quot;My Parse App&quot;&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;css/reset.css&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;css/styles.css&quot;&gt;
  &lt;script src=&quot;http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;http://www.parsecdn.com/js/parse-1.0.19.min.js&quot;&gt;&lt;/script&gt;
    &lt;style&gt;
        body {
            font-family: &quot;HelveticaNeue-Light&quot;, sans-serif;
            font-weight:300;
        }
        h2 {
            font-size:16px;
            text-transform:uppercase;
        }
        a {
            text-decoration:none;
        }
        .hidden {
            display:none;
        }
        #main {
            text-align:center;
        }
        input {
            padding: 10px;
            border-radius: 3px;
            border:1px solid #ccc;
            box-shadow: inset 0 0 10px #eee;
            font-size:24px;
        }
        #input-wrapper {
            padding-bottom:15px;
        }
        #list-item-submit {
            background: #73D175;
            color: white;
            box-shadow:none;
            border-color: #599E5A;
        }
        li {
            text-align:left;
            font-family:sans-serif;
            list-style: none;
            padding: 10px 0;
            border-bottom:1px solid #ccc;
            margin-left:-10px;
        }
        li input {
            margin-right:15px;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Todo List built on &lt;a href=&quot;http://www.parse.com&quot; alt=&quot;Parse&quot;&gt;Parse&lt;/a&gt;&lt;/h1&gt;
  &lt;div id=&quot;main&quot;&gt;
        &lt;div id=&quot;input-wrapper&quot;&gt;
            &lt;input type=&quot;text&quot; id=&quot;list-input&quot; placeholder=&quot;Enter a todo here...&quot;&gt;
            &lt;input type=&quot;button&quot; id=&quot;list-item-submit&quot; value=&quot;Add&quot;&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;h2&gt;Incomplete Tasks&lt;/h2&gt;
            &lt;ul id=&quot;incomplete-items&quot;&gt;
                &lt;li id=&quot;no-incomplete-message&quot;&gt;There are no incomplete tasks! Consider adding one above.&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
  &lt;/div&gt;
    &lt;!-- This is a template that we'll be using to populate our list items --&gt;
    &lt;script id=&quot;todo-items-template&quot; type=&quot;x/handlebars&quot;&gt;
        &lt;li class=&quot;list-item&quot;&gt;&lt;input type=&quot;checkbox&quot; id=&quot;{id}&quot;&gt;{content}&lt;/li&gt;
    &lt;/script&gt;
    &lt;script&gt;
        //Use the YUI 'node' module.
        YUI().use('node', function(Y) {
            //Lets declare some variables that we'll be using.
            var ListItem,
            query,
            noTasksMessage = Y.one('#no-incomplete-message'),
            submitBtn = Y.one(&quot;#list-item-submit&quot;),
            incompleteItemList = Y.one('#incomplete-items'),
            completeItemList = Y.one('#complete-items'),
            input = Y.one(&quot;#list-input&quot;);
            //The rest of our application code will go below.
            submitBtn.on('click', function(e) {
                /*
                When the submit button is clicked, we want to get the contents of the input and save a new todo list item.
                */
            });
            /*
            When a &lt;li&gt; is clicked, we want to save that item as being complete. We use 'delegate' here instead of 'on' so that we only create one event listener instead of one for each checkbox.
            */
            incompleteItemList.delegate('click', function(e) {
            }, 'li');
            /* We also want to get the 10 most recent incomplete tasks and add them to &lt;div id=&quot;incomplete-items&quot;&gt;&lt;/div&gt; */
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>The important thing to note in the above code is the inclusion of the Parse JavaScript file, <code>&lt;script src="http://www.parsecdn.com/js/parse-1.0.19.min.js"&gt;&lt;/script&gt;</code>. This file contains the Parse object that we will interact with.</p><h3>Add Classes in the Data Browser</h3><blockquote
class="pullquote"><p>Parse frees you from setting up a server-side stack.</p></blockquote><p>Let&#8217;s get back to Parse. View the Data Browser for EnvatoTodo (it&#8217;s currently empty). The Data Browser is similar to a MySQL database server, but the Parse DB is schema-less. While you can specify columns in the Data Browser, you can actually save any object with simple JSON (not unlike many NoSQL/Document databases). This is an extremely important and useful feature of Parse.</p><p>We&#8217;re going to go ahead and add a &#8220;class&#8221; to the database. Think of a class as a table. The reason it&#8217;s called a class is because you&#8217;ll generally create objects from a certain class and then save that object to the database.</p><p><strong>Disclaimer:</strong> JavaScript does not officially have classes (yet), but it does have the logical equivalent. For the sake of simplicity, I will use the terminology &#8220;class&#8221; in this tutorial.</p><p>Parse has five types of classes.</p><ul><li><strong>User classes</strong> store user-specific information, and Parse provides sugar methods such as <code>signUp()</code>, <code>login()</code>, and more to help with user administration.</li><li><strong>Installation classes</strong> are typically used to send push notifications for mobile apps. Yes, Parse supports push notifications to all clients.</li><li><strong>Role classes</strong> help segregate users into specific roles, controlling access to read/write to other classes. This is called ACL (access control list) within Parse.</li><li><strong>Product classes</strong> store in-app product data.</li><li><strong>Custom classes</strong> are for anything else.</li></ul><p>Let&#8217;s create a custom class called <code>ListItem</code>. Once it&#8217;s created, you&#8217;ll notice it already has four properties. Parse automatically updates the properties of every class that you create. Some classes, such as user classes, may have their own specific properties.</p><p>Our <code>ListItem</code> objects will contain a <code>content</code> property to show what the Todo contains, and an <code>isComplete</code> property to indicate whether the Todo was completed. We could add columns for these properties, but Parse will figure it out from our JSON.</p><h3>Initializing Parse</h3><p>Let&#8217;s go back to <code>index.html</code> to add some code. The first thing we want to do is initialize Parse with our App ID and JavaScript key. These can be found under the Overview tab of your application inside the Data Browser. Add the following line to your JavaScript, replacing <code>APP_ID</code> and <code>JS_KEY</code> with the appropriate values:</p><pre class="brush: jscript; title: ; notranslate">
Parse.initialize(APP_ID, JS_KEY);
</pre><h3>Saving Todos</h3><p>Let&#8217;s start adding functionality to our application. We&#8217;ll first save a To-do list item when the user clicks the add button. The following code is all we need for this functionality:</p><pre class="brush: jscript; title: ; notranslate">
submitBtn.on('click', function(e) {
    //Extend the native Parse.Object class.
    var ListItem = Parse.Object.extend(&quot;ListItem&quot;);
    //Instantiate an object of the ListItem class
    var listItem = new ListItem();
    //listItem is now the object that we want to save, so we assign the properties that we want on it.
    listItem.set(&quot;content&quot;, text);
    listItem.set(&quot;isComplete&quot;, false);
    //We call the save method, and pass in success and failure callback functions.
    listItem.save(null, {
        success: function(item) {
        //Success Callback
    },
    error: function(gameScore, error) {
        //Failure Callback
    }
    });
});
</pre><p>Interacting with the database is extremely painless! Every custom class in Parse inherits from <code>Parse.Object</code>; therefore, <code>ListItem</code> is a subclass. The string argument <code>"ListItem"</code> tells Parse that this class correlates to the ListItem table that we created. Then we create a new <code>ListItem</code> object, set its properties, and call <code>save()</code>.</p><h3>Showing Items</h3><p>In order to display a list of To-do items, we&#8217;ll use the <a
href="https://parse.com/docs/js_guide">Parse JavaScript API</a> to query the ten most recently saved items, and list those below the app. This will give you an idea as to how queries work in Parse.</p><pre class="brush: jscript; title: ; notranslate">
//Once again, we extend the Parse.Object class to make the ListItem class
ListItem = Parse.Object.extend(&quot;ListItem&quot;);
//This time, we use Parse.Query to generate a new query, specifically querying the ListItem table.
query = new Parse.Query(ListItem);
//We set constraints on the query.
query.equalTo('isComplete', false)
query.limit = 10;
query.descending('createdAt');
//We submit the query and pass in callback functions.
query.find({
  success: function(results) {
    //Success callback
  },
  error: function(error) {
    //Error Callback
  }
});
</pre><p>Once again, it&#8217;s fairly simple and easy to read. The <code>Parse.Query()</code> method is quite powerful. Here, we perform a fairly basic query, but Parse queries can be complex as well. You can query for specific regular expressions, perform relational queries, and many more. Be sure to visit the <a
href="https://parse.com/docs/js_guide#queries">Query Documentation</a> for more examples and code snippets.</p><h3>Putting it all together</h3><p>The next thing we need to add is the ability to mark a to-do item as complete when checking the item&#8217;s checkbox. Each checkbox has a unique <code>id</code> associated with the Parse object that it represents. Therefore, when a checkbox is clicked, we need to:</p><ul><li>Get the id.</li><li>Query for a Parse object with that id.</li><li>Get the returned Parse object, and update it&#8217;s <code>isComplete</code> property as <code>true</code>.</li><li>Save the updated object.</li><li>Remove it from the displayed list.</li></ul><p>Here&#8217;s what that code looks like:</p><pre class="brush: jscript; title: ; notranslate">
incompleteItemList.delegate('click', function (e) {
    //keep a reference to this
    var self = this;
    //create a Parse query object
    var query = new Parse.Query(ListItem);
    //The query.get() method requires the objectId as its first argument. It returns the object with that id.
    query.get(self.one('input').get('id'), {
      success: function(item) {
        //Once the object is returned, we update its property and save it.
        item.set('isComplete', true);
            item.save();
            //Since the item is no longer incomplete, we remove it from the list.
            self.remove();
            //If there's nothing in the list, show a message saying the list is empty.
            if (incompleteItemList.all('li').size() &gt;= 1) {
                noTasksMessage.removeClass('hidden');
            }
      },
      error: function(object, error) {
            alert(&quot;Error when updating todo item: &quot; + error.code + &quot; &quot; + error.message);
      }
    });
}, 'li');
</pre><p>In this snippet, we query for an individual element with a specific <code>id</code>, update it, and save it. Then we remove it from the list with <code>self.remove()</code>.</p><p>In Parse, updating objects is very similar to saving objects&#8211;we call <code>save()</code> in both cases. Parse figures out whether it&#8217;s an existing (dirty) object, or an entirely new object and performs the appropriate action.</p><h3>Complete Source Code</h3><p>With that, we&#8217;re good to go! Pretty easy, eh? Download the attached ZIP file and open <code>index.html</code> to view the entire source code.</p><hr
/><h2>Other Features</h2><p>In this tutorial, we primarily looked at Parse from a web development point-of-view. However, the service was originally started with mobile developers in mind. Parse has a very thorough SDK for Android and iOS, and it supports features such as push notifications to all users of your mobile app.</p><blockquote><p>Some other big features that we didn&#8217;t cover in this tutorial involve users, roles, and storing relational information.</p></blockquote><p>Parse makes it relatively simple to create users, and assign different roles to them. For example, in a learning management system, you may have &#8220;Teachers&#8221;, &#8220;Students&#8221;, and &#8220;Administrators&#8221;. By assigning roles, you can specify which type of user has access to certain Parse objects.</p><hr
/><h2>What about Security?</h2><blockquote
class="pullquote"><p>A lot of new technologies leverage the cloud&#8230;</p></blockquote><p>As a developer, I like that Parse takes care of a lot of the security concerns that I have. As it states on the website, the Parse SDKs are designed &#8220;so that you typically don&#8217;t need to worry about how data is saved.&#8221; There&#8217;s still the issue of users having access to information that they shouldn&#8217;t be able to. To address this concern, Parse offers Object-level and Class-level permissions.</p><p>Object-level permissions allow a developer to specify an array of object IDs that have access to read and/or write the object. Class-level permissions allow a developer to specify what aspects of a Parse class can be manipulated from the API. The following operations can be allowed or denied on a per-class basis: Get, Find, Update, Create, Delete, and Add Fields.</p><hr
/><h2>Pros and Cons</h2><p>I want to stress is that Parse is not suitable for every type of project. Although the free plan is very generous, Parse is a paid service. It can get <a
href="https://parse.com/plans">expensive</a> if you go above certain limits. Luckily, the pricing model is very transparent, and you should be able to figure out how much your app can cost. Generally speaking, I use it for smaller projects where I can anticipate a certain cap when it comes to the number of API requests that I make. I have yet to try Parse for a large project.</p><blockquote><p>One common issue with a service such as Parse is the lock-in effect.</p></blockquote><p>If you use Parse for a small project that suddenly takes off, it can be difficult to move to a difference service or platform. As you can imagine, replacing Parse with your own back-end would entail a significant amount of refactoring. This doesn&#8217;t mean you shouldn&#8217;t use Parse, but it&#8217;s something to keep in mind.</p><hr
/><h2>Concluding Remarks</h2><p>In this tutorial, we looked at how we can use Parse to create a relatively simple web application. I&#8217;ve used this service for a number of projects for various clients, and I find the Parse team to be very helpful when issues arise. I encourage you give the service a try, and make your own decision!</p><p>Disclosure: I have no relationship with Parse or any of its employees. I&#8217;m just a developer who uses their service, and I find it to be a helpful addition to my development workflow.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/0/da"><img src="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/1/da"><img src="http://feedads.g.doubleclick.net/~a/KdHkxCfP4YcmnzOgFfk-WxyeLTE/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=E_IivGJ37A4:cK2X1Hva7bQ:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=E_IivGJ37A4:cK2X1Hva7bQ:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=E_IivGJ37A4:cK2X1Hva7bQ:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=E_IivGJ37A4:cK2X1Hva7bQ:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/E_IivGJ37A4" height="1" width="1"/>";s:14:"date_timestamp";i:1352826025;}i:1;a:16:{s:5:"title";s:29:"What to Expect From Laravel 4";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/zyYhr2ad3TQ/";s:8:"comments";s:77:"http://net.tutsplus.com/tutorials/php/what-to-expect-from-laravel-4/#comments";s:7:"pubdate";s:31:"Mon, 12 Nov 2012 19:00:08 +0000";s:2:"dc";a:1:{s:7:"creator";s:11:"Jeffrey Way";}s:8:"category";s:16:"PHPlaravelVideos";s:4:"guid";s:32:"http://net.tutsplus.com/?p=28021";s:11:"description";s:4206:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28021&c=355346052' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28021&c=355346052' border='0' alt='' /></a><p> If you&#8217;re keeping up on the latest news in the PHP community, then you likely know that <a
href="http://laravel.com">Laravel 4</a> is on the near horizon. Its creator, Taylor Otwell, recently recorded a handful of screencasts to demonstrate what we can expect, including resourceful controllers, improvements to Eloquent, Composer support, and much more! Take a look after the jump!</p><p><span
id="more-28021"></span></p><hr
/><h2>Basic Routing and Composers</h2><div
class="tutorial_image"> <iframe
width="600" height="450" src="http://www.youtube.com/embed/tX8DC9q6rv0" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/1-basic-routing-and-composers.mp4">Download Video</a></div></div><hr
/><h2>Controllers and Filters</h2><div
class="tutorial_image"> <iframe
width="601" height="338" src="http://www.youtube.com/embed/AjQ5e9TOZVk" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/2-controllers-and-filters.mp4">Download Video</a> and <a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/nettuts-laravel-resource-routes-chart.jpg">Resource Chart</a></div></div><hr
/><h2>IOC Container Basics</h2><div
class="tutorial_image"> <iframe
width="601" height="338" src="http://www.youtube.com/embed/WeB1knLoLYk" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/3-ioc-container-basics.mp4">Download Video</a></div></div><hr
/><h2>Controller Injection and Unit Testing</h2><div
class="tutorial_image"> <iframe
width="601" height="338" src="http://www.youtube.com/embed/QSt9rBa_oUM" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/4-ioc-controller-injection-and-unit-testing.mp4">Download Video</a></div></div><hr
/><h2>Eloquent Collections and Polymorphic Relations</h2><div
class="tutorial_image"> <iframe
width="600" height="338" src="http://www.youtube.com/embed/PzGC4ub6RDg" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/5-eloquent-collections-and-polymorphic-relations.mp4">Download Video</a></div></div><hr
/><h2>Closing Thoughts</h2><p>To stay up to date on the latest Laravel news, be sure to <a
href="http://twitter.com/laravelphp">follow them on Twitter</a>. Also, start getting your bags packed for the first Laravel Conference, coming early 2013!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/0/da"><img src="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/1/da"><img src="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=zyYhr2ad3TQ:7IjmkiBVvls:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=zyYhr2ad3TQ:7IjmkiBVvls:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=zyYhr2ad3TQ:7IjmkiBVvls:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/zyYhr2ad3TQ" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:73:"http://net.tutsplus.com/tutorials/php/what-to-expect-from-laravel-4/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"30";}s:13:"enclosure_url";s:79:"http://nettuts.s3.amazonaws.com/2153_laravel4/1-basic-routing-and-composers.mp4";s:14:"enclosure_type";s:9:"video/mp4";s:16:"enclosure_length";s:8:"24238180";s:10:"feedburner";a:1:{s:8:"origlink";s:68:"http://net.tutsplus.com/tutorials/php/what-to-expect-from-laravel-4/";}s:7:"summary";s:4206:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28021&c=355346052' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=28021&c=355346052' border='0' alt='' /></a><p> If you&#8217;re keeping up on the latest news in the PHP community, then you likely know that <a
href="http://laravel.com">Laravel 4</a> is on the near horizon. Its creator, Taylor Otwell, recently recorded a handful of screencasts to demonstrate what we can expect, including resourceful controllers, improvements to Eloquent, Composer support, and much more! Take a look after the jump!</p><p><span
id="more-28021"></span></p><hr
/><h2>Basic Routing and Composers</h2><div
class="tutorial_image"> <iframe
width="600" height="450" src="http://www.youtube.com/embed/tX8DC9q6rv0" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/1-basic-routing-and-composers.mp4">Download Video</a></div></div><hr
/><h2>Controllers and Filters</h2><div
class="tutorial_image"> <iframe
width="601" height="338" src="http://www.youtube.com/embed/AjQ5e9TOZVk" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/2-controllers-and-filters.mp4">Download Video</a> and <a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/nettuts-laravel-resource-routes-chart.jpg">Resource Chart</a></div></div><hr
/><h2>IOC Container Basics</h2><div
class="tutorial_image"> <iframe
width="601" height="338" src="http://www.youtube.com/embed/WeB1knLoLYk" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/3-ioc-container-basics.mp4">Download Video</a></div></div><hr
/><h2>Controller Injection and Unit Testing</h2><div
class="tutorial_image"> <iframe
width="601" height="338" src="http://www.youtube.com/embed/QSt9rBa_oUM" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/4-ioc-controller-injection-and-unit-testing.mp4">Download Video</a></div></div><hr
/><h2>Eloquent Collections and Polymorphic Relations</h2><div
class="tutorial_image"> <iframe
width="600" height="338" src="http://www.youtube.com/embed/PzGC4ub6RDg" frameborder="0" allowfullscreen></iframe></p><div><a
href="http://d2o0t5hpnwv4c1.cloudfront.net/2153_laravel4/5-eloquent-collections-and-polymorphic-relations.mp4">Download Video</a></div></div><hr
/><h2>Closing Thoughts</h2><p>To stay up to date on the latest Laravel news, be sure to <a
href="http://twitter.com/laravelphp">follow them on Twitter</a>. Also, start getting your bags packed for the first Laravel Conference, coming early 2013!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/0/da"><img src="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/1/da"><img src="http://feedads.g.doubleclick.net/~a/hg9sEPp43JuIcry9wyzLv1j6jSI/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=zyYhr2ad3TQ:7IjmkiBVvls:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=zyYhr2ad3TQ:7IjmkiBVvls:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=zyYhr2ad3TQ:7IjmkiBVvls:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=zyYhr2ad3TQ:7IjmkiBVvls:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/zyYhr2ad3TQ" height="1" width="1"/>";s:14:"date_timestamp";i:1352746808;}i:2;a:13:{s:5:"title";s:47:"20 All Too Common Coding Pitfalls For Beginners";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/beiX3jlVpNE/";s:8:"comments";s:106:"http://net.tutsplus.com/tutorials/tools-and-tips/20-all-too-common-coding-pitfalls-for-beginners/#comments";s:7:"pubdate";s:31:"Sat, 10 Nov 2012 18:34:31 +0000";s:2:"dc";a:1:{s:7:"creator";s:12:"Patkos Csaba";}s:8:"category";s:48:"Tools & TipsTutorialsbest practicesjavascriptphp";s:4:"guid";s:32:"http://net.tutsplus.com/?p=27963";s:11:"description";s:26762:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27963&c=1138485472' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27963&c=1138485472' border='0' alt='' /></a><p>Regardless of our current skill level, we all were beginners at one point in time. Making classic beginner mistakes comes with the territory. Today, we&#8217;ve asked a variety of Nettuts+ staff authors to chime in with their list of pitfalls and solutions &#8211; in a variety of languages.</p><p>Learn from our mistakes; don&#8217;t do these things!</p><p><span
id="more-27963"></span></p><hr
/><h2>JavaScript Tips</h2><h3><span>1 -</span> Unnecessary DOM Manipulation</h3><p>The DOM is slow. Limiting your interaction with it will greatly increase your code&#8217;s performance. Consider the following (bad) code:</p><pre class="brush: jscript; title: ; notranslate">
// anti-pattern
for (var i = 0; i &lt; 100; i++){
	var li = $(&quot;&lt;li&gt;&quot;).html(&quot;This is list item #&quot; + (i+1));
	$(&quot;#someUL&quot;).append(li);
}
</pre><p>This code actually <em>modifies</em> the DOM 100 times, and unnecessarily creates 100 jQuery objects. 100! A more correct approach would be to either use a document fragment, or build up a string that contains the 100 <code>&lt;li/&gt;</code> elements, and then appends that HTML to the containing element. That way, you jump into the DOM a total of once. Here&#8217;s an example:</p><pre class="brush: jscript; title: ; notranslate">
var liststring = &quot;&quot;;
for (var i = 100; i &gt; 0; i--){
	liststring += &quot;&lt;li&gt;This is list item #&quot; + (99- i);
}
document.getElementById(&quot;someUL&quot;).innerHTML(liststring);
</pre><p>As noted above, with this technique, we touch the DOM only once, which is an improvement, but it also relies on string concatenation to build a large string. There&#8217;s a different way that we could approach this, using arrays.</p><pre class="brush: jscript; title: ; notranslate">
var liststring = &quot;&lt;li&gt;&quot;
var lis = [];
for (var i = 100; i &gt; 0; i--){
	lis.push(&quot;This is list item #&quot; + (99- i));
}
liststring += lis.join(&quot;&lt;/li&gt;&lt;li&gt;&quot;) + &quot;&lt;/li&gt;&quot;;
document.getElementById(&quot;someUL&quot;).innerHTML(liststring);
</pre><p>When building large strings, storing each piece of the string as an item within an array element and calling <code>join()</code> is more efficient than string concatenation. This is one of the fastest and easiest ways to build repetitive HTML in JavaScript without using a template library or framework.</p><h3><span>2 -</span> Inconsistent Variable &amp; Function Names in JavaScript</h3><p>This next item isn&#8217;t a performance issue, but is extremely important &#8211; especially if you are working on code that other people work on, as well. Keep your identifiers (variable and function names) consistent. Consider the following variables as an example:</p><pre class="brush: jscript; title: ; notranslate">var foo = &quot;bar&quot;;
var plant = &quot;green&quot;;
var car = &quot;red&quot;;
</pre><p>It wouldn&#8217;t make sense to add another variable, called <code>Something</code>. This introduces inconsistency in your variable naming pattern, causing your brain to cognitively flag this variable as being different or special. This is why constants in most languages are traditionally defined with all caps.</p><p>You can take this a step further by maintaining similar length, grammatical structure, and explanatory nature when naming functions. For example, consider the following contrived function:</p><pre class="brush: jscript; title: ; notranslate">function subtractFive(number){
	return number - 5;
}
</pre><p>Naming a function that adds five to a given number should follow the same pattern, shown here:</p><pre class="brush: jscript; title: ; notranslate">function addFive(number){
	return number + 5;
}
</pre><p>Sometimes, you might name a function to indicate its return value. For instance, you might name a function that returns an HTML string <code>getTweetHTML()</code>. You might also prepend a function&#8217;s name with <code>do</code>, if the function simply performs an operation and doesn&#8217;t return a value, eg: <code>doFetchTweets()</code>.</p><p>Constructor functions typically follow the tradition of classes in other languages, capitalizing the first letter:</p><pre class="brush: jscript; title: ; notranslate">function Dog(color){
	this.color = color;
}
</pre><p>As a general rule of thumb, you should be descriptive when naming your identifiers. Classify them together with other similar identifiers by maintaining a naming pattern that is readable and offers hints to the nature of a variable or function&#8217;s purpose.</p><h3><span>3 -</span> Use <code>hasOwnProperty()</code> in <code>for...in</code> Loops</h3><p>JavaScript&#8217;s arrays are not associative; trying to use them as such is frowned upon by the community. Objects, on the other hand, can be treated as hash tables, and you can iterate over an object&#8217;s properties by using the <code>for...in</code> loop, like so:</p><pre class="brush: jscript; title: ; notranslate">for (var prop in someObject) {
    alert(someObject[prop]); // alert's value of property
}</pre><p>The problem, however, is that the <code>for...in</code> loop iterates over every enumerable property on the object&#8217;s prototype chain. This can be problematic if you only want to use the properties that exist on the actual object.</p><p>You can solve this issue by using the <code>hasOwnProperty()</code> method. Here&#8217;s an example:</p><pre class="brush: jscript; title: ; notranslate">
for (var prop in someObject) {
    if (someObject.hasOwnProperty(prop)) {
        alert(someObject[prop]); // alert's value of property
    }
}</pre><p>This version only alerts the values of the properties that directly reside on <code>someObject</code>.</p><h3><span>4 -</span> Comparing Boolean Values</h3><p>Comparing boolean values in a condition is a waste of computation time. Take a look at the following for an example:</p><pre class="brush: jscript; title: ; notranslate">if (foo == true) {
    // do something for true
} else {
    // do something for false
}</pre><p>Notice the condition: <code>foo == true</code>. The comparison of <code>foo</code> and <code>true</code> is unnecessary because <code>foo</code> is already a boolean value (or it&#8217;s a truthy or falsey one). Instead of comparing <code>foo</code>, simply use it as the condition, like this:</p><pre class="brush: jscript; title: ; notranslate">if (foo) {
    // do something for true
} else {
    // do something for false
}</pre><p>To test for <code>false</code>, use the logical NOT operator, as shown below:</p><pre class="brush: jscript; title: ; notranslate">if (!foo) {
    // do something if foo is false
} else {
    // do something if foo is true
}</pre><h3><span>5 -</span> Event Binding</h3><p>Events are a complicated subject in JavaScript. Gone are the days of inline <code>onclick</code> event handlers (except in some very rare &#8220;splash page&#8221; cases). Instead, use event bubbling and delegation.</p><p>Let&#8217;s imagine that you have a grid of pictures that need to launch a modal lightbox window. Here&#8217;s what you <em>shouldn&#8217;t</em> do. Note: we&#8217;re using jQuery here, assuming you are using a similar library. If not, the same bubbling principles also apply to vanilla JavaScript.</p><p>The relevant HTML:</p><pre class="brush: xml; title: ; notranslate">&lt;div id=&quot;grid-container&quot;&gt;
	&lt;a href=&quot;someimage.jpg&quot;&gt;&lt;img src=&quot;someimage-thumb.jpg&quot;&gt;&lt;/a&gt;
	&lt;a href=&quot;someimage.jpg&quot;&gt;&lt;img src=&quot;someimage-thumb.jpg&quot;&gt;&lt;/a&gt;
	&lt;a href=&quot;someimage.jpg&quot;&gt;&lt;img src=&quot;someimage-thumb.jpg&quot;&gt;&lt;/a&gt;
	...
&lt;/div&gt;</pre><p>The (bad) JavaScript:</p><pre class="brush: jscript; title: ; notranslate">$('a').on('click', function() {
	callLightbox(this);
});</pre><p>This code assumes that calling the lightbox involves passing an anchor element that references the full size image. Instead of binding to each anchor element, bind to the <code>#grid-container</code> element instead.</p><pre class="brush: jscript; title: ; notranslate">$(&quot;#grid-container&quot;).on(&quot;click&quot;, &quot;a&quot;, function(event) {
	callLightbox(event.target);
});</pre><p>In this code, both <code>this</code> and <code>event.target</code> refer to the anchor element. You can use this same technique with any parent element. Just make sure to define the element that should be the event&#8217;s target.</p><h3><span>6 -</span> Avoid Ternary Redundancy</h3><p>The overuse of ternary statements is quite common both in JavaScript and PHP.</p><pre class="brush: jscript; title: ; notranslate">
// javascript
return foo.toString() !== &quot;&quot; ? true : false;
</pre><pre class="brush: php; title: ; notranslate">
// php
return (something()) ? true : false;
</pre><p>A condition expression always returns a <code>true</code> or <code>false</code> value, meaning you don&#8217;t need to explicitly add <code>true</code>/<code>false</code> as ternary values. Instead, you could simply return the condition:</p><pre class="brush: jscript; title: ; notranslate">
// javascript
return foo.toString() !== &quot;&quot;;
</pre><pre class="brush: php; title: ; notranslate">
// php
return something();
</pre><hr
/><h2>PHP Tips</h2><h3><span>7 -</span> Use Ternary When Appropriate</h3><p><code>if...else</code> statements are a central part of most languages. But doing something simple, such as assigning a value to a variable based upon a condition &#8211; well, they can junk up your code. Consider the following code:</p><pre class="brush: php; title: ; notranslate">if ($greeting)
{
    $post-&gt;message = 'Hello';
}
else
{
    $post-&gt;message = 'Goodbye';
}</pre><p>This code can be reduced to one line, while still maintaining readability by using the ternary operator, like this:</p><pre class="brush: php; title: ; notranslate">$post-&gt;message = $greeting ? 'Hello' : 'Goodbye';</pre><p>It&#8217;s clear, concise, and gives you the functionality you need.</p><blockquote><p>As useful as the ternary operator is, the most important guideline is not to over-use it! The goal of coding is not to cramp your logic into as few lines as possible.</p></blockquote><h3><span>8 -</span> Throw Exceptions Instead of Inception-Style Nesting</h3><p>Let&#8217;s face it: many levels of nesting is ugly and difficult to maintain/read. The following code is a relatively simplified example, but they get much worse over time:</p><pre class="brush: php; title: ; notranslate">
// anti-pattern
$error_message = null;
if ($this-&gt;form_validation-&gt;run())
{
	if ($this-&gt;upload-&gt;do_upload())
	{
		$image = $this-&gt;upload-&gt;get_info();
		if ( ! $this-&gt;image-&gt;create_thumbnail($image['file_name'], 300, 150))
		{
			$error_message = 'There was an error creating the thumbnail.';
		}
	}
	else
	{
		$error_message = 'There was an error uploading the image.';
	}
}
else
{
	$error_message = $this-&gt;form_validation-&gt;error_string();
}
// Show error messages
if ($error_message !== null)
{
	$this-&gt;load-&gt;view('form', array(
		'error' =&gt; $error_message,
	));
}
// Save the page
else
{
	$some_data['image'] = $image['file_name'];
	$this-&gt;some_model-&gt;save($some_data);
}</pre><p>That&#8217;s some nasty code, but you can make it drastically cleaner by using exceptions, like so:</p><pre class="brush: php; title: ; notranslate">try
{
	if ( ! $this-&gt;form_validation-&gt;run())
	{
		throw new Exception($this-&gt;form_validation-&gt;error_string());
	}
	if ( ! $this-&gt;upload-&gt;do_upload())
	{
		throw new Exception('There was an error uploading the image.');
	}
	$image = $this-&gt;upload-&gt;get_info();
	if ( ! $this-&gt;image-&gt;create_thumbnail($image['file_name'], 300, 150))
	{
		throw new Exception('There was an error creating the thumbnail.');
	}
}
// Show error messages
catch (Exception $e)
{
	$this-&gt;load-&gt;view('form', array(
		'error' =&gt; $e-&gt;getMessage(),
	));
	// Stop method execution with return, or use exit
	return;
}
// Got this far, must not have any trouble
$some_data['image'] = $image['file_name'];
$this-&gt;some_model-&gt;save($some_data);</pre><p>It might be the same number of lines, but it allows for considerably more readable and maintainable code. It also avoids those difficult debugging sessions, where you&#8217;ve missed a possible path through the <code>if</code> statement. Keep it simple!</p><h3><span>9 -</span> <code>False</code>-Happy Methods</h3><blockquote
class="pullquote"><p>Being exception-happy is far more advantageous than being false-happy.</p></blockquote><p>Ruby or Python developers are used to watching for trivial exceptions. While that sound tedious, it&#8217;s actually quite a good thing. If anything goes wrong, an exception is thrown, and you instantly know where the problem is.</p><p>In PHP &#8211; and especially when using older frameworks, such as CodeIgniter &#8211; you get what I refer to as &#8220;false-happy code&#8221; (as opposed to exception-happy). Instead of having an exception get all up in your face, it just returns a <code>false</code> value and assigns the error string to some other property. This forces you to fish it out of the class using a <code>get_error();</code> method.</p><p>Being exception-happy is far more advantageous than being false-happy. If an error occurs within your code (eg: could not connect to S3 to upload an image, or a value is empty, etc.), then throw an exception. You can also throw specific types of exceptions by extending the <code>Exception</code> class, like so:</p><pre class="brush: php; title: ; notranslate">class CustomException extends Exception {}</pre><p>Throwing a custom exception makes debugging considerably easier.</p><h3><span>Tip 10 -</span> Use Guard Clauses</h3><p>It&#8217;s common to use <code>if</code> statements to control a function or method&#8217;s execution path. It&#8217;s tempting to test a condition and execute a lot of code when the condition results in <code>true</code>, only to simply return in the <code>else</code> statement. For example:</p><pre class="brush: php; title: ; notranslate">
function someFunction($param) {
    if ($param == 'OK') {
       $this-&gt;doSomething();
       return true;
    } else {
       return false;
    }
}</pre><p>This kind of solution, however, represents a potential for spaghetti code. You can make this code easier to read by reversing the condition. Here&#8217;s the better version:</p><pre class="brush: php; title: ; notranslate">function someFunction($param) {
    if ($param != 'OK') return false;
    $this-&gt;doSomething();
    return true;
}</pre><p>Isn&#8217;t that easier to read? It&#8217;s a simple change that makes a drastic difference in the readability of your code.</p><h3><span>Tip 11 &#8211; </span> Use <code>while</code> for Simple Iterations</h3><p>The <code>for</code> loop is commonly used when you need, for example, a counter. Here&#8217;s a simple <code>for</code> loop:</p><pre class="brush: php; title: ; notranslate">for (var i = 0; i &lt; x; i++) {
    ...
}</pre><p>There are some very good reasons to use a <code>for</code> loop, but a <code>while</code> loop may be better if you just need something simple, like this:</p><pre class="brush: php; title: ; notranslate">
var i = x;
while (i--) {
    ...
}</pre><p>It doesn&#8217;t work in every situation, but it is an alternative.</p><h3><span>Tip 12 &#8211; </span> Keep Methods Maintainable</h3><blockquote
class="pullquote"><p>This is easily one of the most frequent mistakes made by newcomers.</p></blockquote><p>A method is an object&#8217;s unit of work, and limiting your methods to a maintainable size makes your code easier to read and maintain. Take a look at the following monster method:</p><pre class="brush: php; title: ; notranslate">class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this-&gt;goAndDressUp();
			$this-&gt;washYourTeeth();
			$this-&gt;cleanYourWeapon();
			$this-&gt;takeYourHelmet();
			if($this-&gt;helmetDoesNotFit())
				$this-&gt;takeAHat();
			else
				$this-&gt;installHelmet();
			$this-&gt;chekcYourKnife();
			if($this-&gt;myAirplain() == &quot;F22&quot;)
				$this-&gt;goToArmyAirport();
			else
				$this-&gt;goToCivilianAirport();
			$this-&gt;aim();
			$this-&gt;prepare();
			$this-&gt;fire();
		}
	}
}</pre><p>Consider breaking this monster method into smaller, descriptive chunks, each being responsible for performing one well-abstracted action. This is easily one of the most frequent mistakes made by newcomers.</p><pre class="brush: php; title: ; notranslate">class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this-&gt;prepareYourself();
			$this-&gt;tryHelmet();
			$this-&gt;findYourAirport();
			$this-&gt;fightEnemy();
		}
	}
	private function prepareYourself() {
		$this-&gt;goAndDressUp();
		$this-&gt;washYourTeeth();
		$this-&gt;cleanYourWeapon();
		$this-&gt;chekcYourKnife();
	}
	private function tryHelmet() {
		$this-&gt;takeYourHelmet();
		if($this-&gt;helmetDoesNotFit())
			$this-&gt;takeAHat();
		else
			$this-&gt;installHelmet();
	}
	private function findYourAirport() {
		if($this-&gt;myAirplain() == &quot;F22&quot;)
			$this-&gt;goToArmyAirport();
		else
			$this-&gt;goToCivilianAirport();
	}
	private function fightEnemy() {
		$this-&gt;aim();
		$this-&gt;prepare();
		$this-&gt;fire();
	}
}</pre><p>There we go: cleaner, and easier to debug!</p><h3><span>Step 13 -</span> Avoid Deep Nesting</h3><p>Too many levels of nesting makes code difficult to read and maintain. Consider the following:</p><pre class="brush: php; title: ; notranslate">function doSomething() {
    if ($someCondition) {
        if ($someOtherCondition) {
            if ($yetSomeOtherCondition) {
                doSomethingSpecial();
            }
            doSomethingElse();
        }
    }
}</pre><p>You can refer to Tip #10 to make this code easier to read by reversing some of the conditions.</p><pre class="brush: php; title: ; notranslate">function doSomething() {
    if (!$someCondition) {
        return false;
    }
    if (!$someOtherCondition) {
        return false;
    }
    if ($yetSomeOtherCondition) {
        doSomethingSpecial();
    }
    doSomethingElse();
}</pre><p>This code is considerably cleaner and produces the same results as before.</p><p>When you find yourself with nested <code>if</code> statements, closely examine your code; your method may be performing more than one task. Here&#8217;s an example:</p><pre class="brush: php; title: ; notranslate">function someFunc() {
	if($oneThing) {
		$this-&gt;doSomething();
		if($anotherThing)
			$this-&gt;doSomethingElse();
	}
}</pre><p>In these cases, extract the nested methods into their own method:</p><pre class="brush: php; title: ; notranslate">function someFunc() {
	if($oneThing) {
		$this-&gt;doSomething();
		$this-&gt;doAnotherThing($anotherThing);
	}
}
private doAnotherThing($anotherThing) {
	if($anotherThing)
		$this-&gt;doSomethingElse();
}</pre><h3><span>Tip 14 &#8211; </span> Avoid Magic Numbers and Strings</h3><p>Magic numbers and strings are evil. Define variables or constants with the values you want to use in your code.</p><p>Instead of this:</p><pre class="brush: php; title: ; notranslate">function someFunct() {
	$this-&gt;order-&gt;set(23);
	$this-&gt;order-&gt;addProduct('superComputer');
	$this-&gt;shoppingList-&gt;add('superComputer');
}</pre><p>Specify what those numbers and strings mean, and assign them to a variable with a meaningful name, like this:</p><pre class="brush: php; title: ; notranslate">function someFunct() {
	$orderId = 23;
	$selectedProductName = 'superComputer';
	$this-&gt;order-&gt;set($orderId);
	$this-&gt;order-&gt;addProduct($selectedProductName);
	$this-&gt;shoppingList-&gt;add($selectedProductName);
}</pre><blockquote><p>While some might argue that we&#8217;re needlessly creating variables, the performance hit is negligible. Readability always takes priority. Remember: don&#8217;t optimize for performance until you can describe why it&#8217;s necessary.</p></blockquote><h3><span>Step 15 -</span> Use Built-In Array Functions</h3><p>Use the built-in array functions instead of <code>foreach()</code>.</p><p>Not Ideal:</p><pre class="brush: php; title: ; notranslate">foreach (&amp;$myArray as $key =&gt;$element) {
   if ($element &gt; 5) unset ($myArray[$key]);
}
</pre><p>Better:</p><pre class="brush: php; title: ; notranslate">$myArray = array_filter($myArray, function ($element) { return $element &lt;= 5;});
</pre><p>PHP offers a variety of array methods. They&#8217;re confusing at first, but take a day and try to learn as many as possible.</p><h3><span>Tip 16 -</span> Don&#8217;t Overuse Variables</h3><p>It&#8217;s easy to overuse variables, but remember that variables are stored in memory. For every variable you create, the system needs to allocate memory for that variable. Look at this code:</p><pre class="brush: php; title: ; notranslate">public function get_posts() {
	$query = $this-&gt;db-&gt;get('posts');
	$result = $query-&gt;result();
	return $result;
}</pre><p>The <code>$result</code> variable isn&#8217;t necessary. The following code omits that variable:</p><pre class="brush: php; title: ; notranslate">public function get_posts() {
	$query = $this-&gt;db-&gt;get('posts');
	return $query-&gt;result();
}
</pre><p>The difference is subtle, but we were able to improve this simple example. We kept the <i>$query</i> variable because it relates to the database, while <i>$result</i> related more to our logic.</p><hr
/><h2>General Programming Recommendations</h2><h3><span>Tip 17 -</span> Rely on the Database Engine</h3><blockquote
class="pullquote"><p>Anything less is a code smell.</p></blockquote><p>A database is designed for working with data; use its tools and abilities to make your application more efficient.</p><p>For example, you can avoid redundant database queries in many circumstances. Most plug-and-play user management scripts use two queries for user registration: one to check whether the e-mail/username already exists and another to actually add it to the database. A much better approach is to set the username field to <code>UNIQUE</code>. You can then use native MySQL functions to check whether or not the record was added to the database.</p><h3><span>Tip 18:</span> Properly Name Your Variables</h3><p>The days of naming your variables <code>x</code>, <code>y</code>, <code>z</code> are over (unless, of course, you&#8217;re dealing with a coordinate system). A variable represents an important part of your logic. Don&#8217;t want to type a long name? Get a better IDE. Modern IDEs auto-complete variable names in a blink of an eye.</p><blockquote><p> Always be coding for six months from now. Are you certain that you&#8217;ll remember what that <code>$sut</code> variables refers to a year from now? Likely not: be descriptive. Anything less is a code smell.</p></blockquote><h3><span>Tip 19 -</span> Methods Represent Actions</h3><blockquote
class="pullquote"><p>Mistakes happen; the key is to learn from them.</p></blockquote><p>Name your methods with verbs representing the action they perform. The main concept is the exact opposite of the variable naming scheme. Use a short, but descriptive, name in a large scope (ie: public methods), and use a longer and more detailed name in a short scope (ie: private / protected methods). This helps make your code read like well written prose.</p><p>Also avoid any language other than English, when naming your methods. It&#8217;s annoying to read function names like 做些什麼() or делатьчтото() in your project. It may be impossible for other programmers to understand your intent. While it might seem arrogant, for better or worse, English is the adopted language of code. Try to use it, if we&#8217;re working on a large team.</p><h3><span>Tip 20:</span> Structure Recommendations</h3><p>Finally, code structure is just as important to readability and maintainability as anything else we&#8217;ve talked about today. Here are two recommendations:</p><ul><li>Indent with four or two space-width tabs. Anything more, such as eight spaces, is too much and will make your code difficult to read.</li><li>Set a reasonable line-width and respect it. Forty characters in a line? We&#8217;re not in the &#8217;70s any more; set your limit to 120 characters, put a mark on the screen, and force yourself or your IDE to respect that limit. 120 characters gives you a nice width without making you scroll.</li></ul><hr
/><h2>Conclusion</h2><blockquote><p>&#8220;I&#8217;ve never made a stupid programming mistake.&#8221; &#8212; No one, ever.</p></blockquote><p>Mistakes happen; the key is to learn from them. We at Nettuts+ have made, and will continue to make, mistakes. Our hope is that you learn from our mistakes so that you can avoid them in the future. But, to be honest, the best way to learn best practices is to make the mistakes yourself!</p><p>Thanks for reading!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/0/da"><img src="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/1/da"><img src="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=beiX3jlVpNE:I5zwCQjpQGg:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=beiX3jlVpNE:I5zwCQjpQGg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=beiX3jlVpNE:I5zwCQjpQGg:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/beiX3jlVpNE" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:102:"http://net.tutsplus.com/tutorials/tools-and-tips/20-all-too-common-coding-pitfalls-for-beginners/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"72";}s:10:"feedburner";a:1:{s:8:"origlink";s:97:"http://net.tutsplus.com/tutorials/tools-and-tips/20-all-too-common-coding-pitfalls-for-beginners/";}s:7:"summary";s:26762:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27963&c=1138485472' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27963&c=1138485472' border='0' alt='' /></a><p>Regardless of our current skill level, we all were beginners at one point in time. Making classic beginner mistakes comes with the territory. Today, we&#8217;ve asked a variety of Nettuts+ staff authors to chime in with their list of pitfalls and solutions &#8211; in a variety of languages.</p><p>Learn from our mistakes; don&#8217;t do these things!</p><p><span
id="more-27963"></span></p><hr
/><h2>JavaScript Tips</h2><h3><span>1 -</span> Unnecessary DOM Manipulation</h3><p>The DOM is slow. Limiting your interaction with it will greatly increase your code&#8217;s performance. Consider the following (bad) code:</p><pre class="brush: jscript; title: ; notranslate">
// anti-pattern
for (var i = 0; i &lt; 100; i++){
	var li = $(&quot;&lt;li&gt;&quot;).html(&quot;This is list item #&quot; + (i+1));
	$(&quot;#someUL&quot;).append(li);
}
</pre><p>This code actually <em>modifies</em> the DOM 100 times, and unnecessarily creates 100 jQuery objects. 100! A more correct approach would be to either use a document fragment, or build up a string that contains the 100 <code>&lt;li/&gt;</code> elements, and then appends that HTML to the containing element. That way, you jump into the DOM a total of once. Here&#8217;s an example:</p><pre class="brush: jscript; title: ; notranslate">
var liststring = &quot;&quot;;
for (var i = 100; i &gt; 0; i--){
	liststring += &quot;&lt;li&gt;This is list item #&quot; + (99- i);
}
document.getElementById(&quot;someUL&quot;).innerHTML(liststring);
</pre><p>As noted above, with this technique, we touch the DOM only once, which is an improvement, but it also relies on string concatenation to build a large string. There&#8217;s a different way that we could approach this, using arrays.</p><pre class="brush: jscript; title: ; notranslate">
var liststring = &quot;&lt;li&gt;&quot;
var lis = [];
for (var i = 100; i &gt; 0; i--){
	lis.push(&quot;This is list item #&quot; + (99- i));
}
liststring += lis.join(&quot;&lt;/li&gt;&lt;li&gt;&quot;) + &quot;&lt;/li&gt;&quot;;
document.getElementById(&quot;someUL&quot;).innerHTML(liststring);
</pre><p>When building large strings, storing each piece of the string as an item within an array element and calling <code>join()</code> is more efficient than string concatenation. This is one of the fastest and easiest ways to build repetitive HTML in JavaScript without using a template library or framework.</p><h3><span>2 -</span> Inconsistent Variable &amp; Function Names in JavaScript</h3><p>This next item isn&#8217;t a performance issue, but is extremely important &#8211; especially if you are working on code that other people work on, as well. Keep your identifiers (variable and function names) consistent. Consider the following variables as an example:</p><pre class="brush: jscript; title: ; notranslate">var foo = &quot;bar&quot;;
var plant = &quot;green&quot;;
var car = &quot;red&quot;;
</pre><p>It wouldn&#8217;t make sense to add another variable, called <code>Something</code>. This introduces inconsistency in your variable naming pattern, causing your brain to cognitively flag this variable as being different or special. This is why constants in most languages are traditionally defined with all caps.</p><p>You can take this a step further by maintaining similar length, grammatical structure, and explanatory nature when naming functions. For example, consider the following contrived function:</p><pre class="brush: jscript; title: ; notranslate">function subtractFive(number){
	return number - 5;
}
</pre><p>Naming a function that adds five to a given number should follow the same pattern, shown here:</p><pre class="brush: jscript; title: ; notranslate">function addFive(number){
	return number + 5;
}
</pre><p>Sometimes, you might name a function to indicate its return value. For instance, you might name a function that returns an HTML string <code>getTweetHTML()</code>. You might also prepend a function&#8217;s name with <code>do</code>, if the function simply performs an operation and doesn&#8217;t return a value, eg: <code>doFetchTweets()</code>.</p><p>Constructor functions typically follow the tradition of classes in other languages, capitalizing the first letter:</p><pre class="brush: jscript; title: ; notranslate">function Dog(color){
	this.color = color;
}
</pre><p>As a general rule of thumb, you should be descriptive when naming your identifiers. Classify them together with other similar identifiers by maintaining a naming pattern that is readable and offers hints to the nature of a variable or function&#8217;s purpose.</p><h3><span>3 -</span> Use <code>hasOwnProperty()</code> in <code>for...in</code> Loops</h3><p>JavaScript&#8217;s arrays are not associative; trying to use them as such is frowned upon by the community. Objects, on the other hand, can be treated as hash tables, and you can iterate over an object&#8217;s properties by using the <code>for...in</code> loop, like so:</p><pre class="brush: jscript; title: ; notranslate">for (var prop in someObject) {
    alert(someObject[prop]); // alert's value of property
}</pre><p>The problem, however, is that the <code>for...in</code> loop iterates over every enumerable property on the object&#8217;s prototype chain. This can be problematic if you only want to use the properties that exist on the actual object.</p><p>You can solve this issue by using the <code>hasOwnProperty()</code> method. Here&#8217;s an example:</p><pre class="brush: jscript; title: ; notranslate">
for (var prop in someObject) {
    if (someObject.hasOwnProperty(prop)) {
        alert(someObject[prop]); // alert's value of property
    }
}</pre><p>This version only alerts the values of the properties that directly reside on <code>someObject</code>.</p><h3><span>4 -</span> Comparing Boolean Values</h3><p>Comparing boolean values in a condition is a waste of computation time. Take a look at the following for an example:</p><pre class="brush: jscript; title: ; notranslate">if (foo == true) {
    // do something for true
} else {
    // do something for false
}</pre><p>Notice the condition: <code>foo == true</code>. The comparison of <code>foo</code> and <code>true</code> is unnecessary because <code>foo</code> is already a boolean value (or it&#8217;s a truthy or falsey one). Instead of comparing <code>foo</code>, simply use it as the condition, like this:</p><pre class="brush: jscript; title: ; notranslate">if (foo) {
    // do something for true
} else {
    // do something for false
}</pre><p>To test for <code>false</code>, use the logical NOT operator, as shown below:</p><pre class="brush: jscript; title: ; notranslate">if (!foo) {
    // do something if foo is false
} else {
    // do something if foo is true
}</pre><h3><span>5 -</span> Event Binding</h3><p>Events are a complicated subject in JavaScript. Gone are the days of inline <code>onclick</code> event handlers (except in some very rare &#8220;splash page&#8221; cases). Instead, use event bubbling and delegation.</p><p>Let&#8217;s imagine that you have a grid of pictures that need to launch a modal lightbox window. Here&#8217;s what you <em>shouldn&#8217;t</em> do. Note: we&#8217;re using jQuery here, assuming you are using a similar library. If not, the same bubbling principles also apply to vanilla JavaScript.</p><p>The relevant HTML:</p><pre class="brush: xml; title: ; notranslate">&lt;div id=&quot;grid-container&quot;&gt;
	&lt;a href=&quot;someimage.jpg&quot;&gt;&lt;img src=&quot;someimage-thumb.jpg&quot;&gt;&lt;/a&gt;
	&lt;a href=&quot;someimage.jpg&quot;&gt;&lt;img src=&quot;someimage-thumb.jpg&quot;&gt;&lt;/a&gt;
	&lt;a href=&quot;someimage.jpg&quot;&gt;&lt;img src=&quot;someimage-thumb.jpg&quot;&gt;&lt;/a&gt;
	...
&lt;/div&gt;</pre><p>The (bad) JavaScript:</p><pre class="brush: jscript; title: ; notranslate">$('a').on('click', function() {
	callLightbox(this);
});</pre><p>This code assumes that calling the lightbox involves passing an anchor element that references the full size image. Instead of binding to each anchor element, bind to the <code>#grid-container</code> element instead.</p><pre class="brush: jscript; title: ; notranslate">$(&quot;#grid-container&quot;).on(&quot;click&quot;, &quot;a&quot;, function(event) {
	callLightbox(event.target);
});</pre><p>In this code, both <code>this</code> and <code>event.target</code> refer to the anchor element. You can use this same technique with any parent element. Just make sure to define the element that should be the event&#8217;s target.</p><h3><span>6 -</span> Avoid Ternary Redundancy</h3><p>The overuse of ternary statements is quite common both in JavaScript and PHP.</p><pre class="brush: jscript; title: ; notranslate">
// javascript
return foo.toString() !== &quot;&quot; ? true : false;
</pre><pre class="brush: php; title: ; notranslate">
// php
return (something()) ? true : false;
</pre><p>A condition expression always returns a <code>true</code> or <code>false</code> value, meaning you don&#8217;t need to explicitly add <code>true</code>/<code>false</code> as ternary values. Instead, you could simply return the condition:</p><pre class="brush: jscript; title: ; notranslate">
// javascript
return foo.toString() !== &quot;&quot;;
</pre><pre class="brush: php; title: ; notranslate">
// php
return something();
</pre><hr
/><h2>PHP Tips</h2><h3><span>7 -</span> Use Ternary When Appropriate</h3><p><code>if...else</code> statements are a central part of most languages. But doing something simple, such as assigning a value to a variable based upon a condition &#8211; well, they can junk up your code. Consider the following code:</p><pre class="brush: php; title: ; notranslate">if ($greeting)
{
    $post-&gt;message = 'Hello';
}
else
{
    $post-&gt;message = 'Goodbye';
}</pre><p>This code can be reduced to one line, while still maintaining readability by using the ternary operator, like this:</p><pre class="brush: php; title: ; notranslate">$post-&gt;message = $greeting ? 'Hello' : 'Goodbye';</pre><p>It&#8217;s clear, concise, and gives you the functionality you need.</p><blockquote><p>As useful as the ternary operator is, the most important guideline is not to over-use it! The goal of coding is not to cramp your logic into as few lines as possible.</p></blockquote><h3><span>8 -</span> Throw Exceptions Instead of Inception-Style Nesting</h3><p>Let&#8217;s face it: many levels of nesting is ugly and difficult to maintain/read. The following code is a relatively simplified example, but they get much worse over time:</p><pre class="brush: php; title: ; notranslate">
// anti-pattern
$error_message = null;
if ($this-&gt;form_validation-&gt;run())
{
	if ($this-&gt;upload-&gt;do_upload())
	{
		$image = $this-&gt;upload-&gt;get_info();
		if ( ! $this-&gt;image-&gt;create_thumbnail($image['file_name'], 300, 150))
		{
			$error_message = 'There was an error creating the thumbnail.';
		}
	}
	else
	{
		$error_message = 'There was an error uploading the image.';
	}
}
else
{
	$error_message = $this-&gt;form_validation-&gt;error_string();
}
// Show error messages
if ($error_message !== null)
{
	$this-&gt;load-&gt;view('form', array(
		'error' =&gt; $error_message,
	));
}
// Save the page
else
{
	$some_data['image'] = $image['file_name'];
	$this-&gt;some_model-&gt;save($some_data);
}</pre><p>That&#8217;s some nasty code, but you can make it drastically cleaner by using exceptions, like so:</p><pre class="brush: php; title: ; notranslate">try
{
	if ( ! $this-&gt;form_validation-&gt;run())
	{
		throw new Exception($this-&gt;form_validation-&gt;error_string());
	}
	if ( ! $this-&gt;upload-&gt;do_upload())
	{
		throw new Exception('There was an error uploading the image.');
	}
	$image = $this-&gt;upload-&gt;get_info();
	if ( ! $this-&gt;image-&gt;create_thumbnail($image['file_name'], 300, 150))
	{
		throw new Exception('There was an error creating the thumbnail.');
	}
}
// Show error messages
catch (Exception $e)
{
	$this-&gt;load-&gt;view('form', array(
		'error' =&gt; $e-&gt;getMessage(),
	));
	// Stop method execution with return, or use exit
	return;
}
// Got this far, must not have any trouble
$some_data['image'] = $image['file_name'];
$this-&gt;some_model-&gt;save($some_data);</pre><p>It might be the same number of lines, but it allows for considerably more readable and maintainable code. It also avoids those difficult debugging sessions, where you&#8217;ve missed a possible path through the <code>if</code> statement. Keep it simple!</p><h3><span>9 -</span> <code>False</code>-Happy Methods</h3><blockquote
class="pullquote"><p>Being exception-happy is far more advantageous than being false-happy.</p></blockquote><p>Ruby or Python developers are used to watching for trivial exceptions. While that sound tedious, it&#8217;s actually quite a good thing. If anything goes wrong, an exception is thrown, and you instantly know where the problem is.</p><p>In PHP &#8211; and especially when using older frameworks, such as CodeIgniter &#8211; you get what I refer to as &#8220;false-happy code&#8221; (as opposed to exception-happy). Instead of having an exception get all up in your face, it just returns a <code>false</code> value and assigns the error string to some other property. This forces you to fish it out of the class using a <code>get_error();</code> method.</p><p>Being exception-happy is far more advantageous than being false-happy. If an error occurs within your code (eg: could not connect to S3 to upload an image, or a value is empty, etc.), then throw an exception. You can also throw specific types of exceptions by extending the <code>Exception</code> class, like so:</p><pre class="brush: php; title: ; notranslate">class CustomException extends Exception {}</pre><p>Throwing a custom exception makes debugging considerably easier.</p><h3><span>Tip 10 -</span> Use Guard Clauses</h3><p>It&#8217;s common to use <code>if</code> statements to control a function or method&#8217;s execution path. It&#8217;s tempting to test a condition and execute a lot of code when the condition results in <code>true</code>, only to simply return in the <code>else</code> statement. For example:</p><pre class="brush: php; title: ; notranslate">
function someFunction($param) {
    if ($param == 'OK') {
       $this-&gt;doSomething();
       return true;
    } else {
       return false;
    }
}</pre><p>This kind of solution, however, represents a potential for spaghetti code. You can make this code easier to read by reversing the condition. Here&#8217;s the better version:</p><pre class="brush: php; title: ; notranslate">function someFunction($param) {
    if ($param != 'OK') return false;
    $this-&gt;doSomething();
    return true;
}</pre><p>Isn&#8217;t that easier to read? It&#8217;s a simple change that makes a drastic difference in the readability of your code.</p><h3><span>Tip 11 &#8211; </span> Use <code>while</code> for Simple Iterations</h3><p>The <code>for</code> loop is commonly used when you need, for example, a counter. Here&#8217;s a simple <code>for</code> loop:</p><pre class="brush: php; title: ; notranslate">for (var i = 0; i &lt; x; i++) {
    ...
}</pre><p>There are some very good reasons to use a <code>for</code> loop, but a <code>while</code> loop may be better if you just need something simple, like this:</p><pre class="brush: php; title: ; notranslate">
var i = x;
while (i--) {
    ...
}</pre><p>It doesn&#8217;t work in every situation, but it is an alternative.</p><h3><span>Tip 12 &#8211; </span> Keep Methods Maintainable</h3><blockquote
class="pullquote"><p>This is easily one of the most frequent mistakes made by newcomers.</p></blockquote><p>A method is an object&#8217;s unit of work, and limiting your methods to a maintainable size makes your code easier to read and maintain. Take a look at the following monster method:</p><pre class="brush: php; title: ; notranslate">class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this-&gt;goAndDressUp();
			$this-&gt;washYourTeeth();
			$this-&gt;cleanYourWeapon();
			$this-&gt;takeYourHelmet();
			if($this-&gt;helmetDoesNotFit())
				$this-&gt;takeAHat();
			else
				$this-&gt;installHelmet();
			$this-&gt;chekcYourKnife();
			if($this-&gt;myAirplain() == &quot;F22&quot;)
				$this-&gt;goToArmyAirport();
			else
				$this-&gt;goToCivilianAirport();
			$this-&gt;aim();
			$this-&gt;prepare();
			$this-&gt;fire();
		}
	}
}</pre><p>Consider breaking this monster method into smaller, descriptive chunks, each being responsible for performing one well-abstracted action. This is easily one of the most frequent mistakes made by newcomers.</p><pre class="brush: php; title: ; notranslate">class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this-&gt;prepareYourself();
			$this-&gt;tryHelmet();
			$this-&gt;findYourAirport();
			$this-&gt;fightEnemy();
		}
	}
	private function prepareYourself() {
		$this-&gt;goAndDressUp();
		$this-&gt;washYourTeeth();
		$this-&gt;cleanYourWeapon();
		$this-&gt;chekcYourKnife();
	}
	private function tryHelmet() {
		$this-&gt;takeYourHelmet();
		if($this-&gt;helmetDoesNotFit())
			$this-&gt;takeAHat();
		else
			$this-&gt;installHelmet();
	}
	private function findYourAirport() {
		if($this-&gt;myAirplain() == &quot;F22&quot;)
			$this-&gt;goToArmyAirport();
		else
			$this-&gt;goToCivilianAirport();
	}
	private function fightEnemy() {
		$this-&gt;aim();
		$this-&gt;prepare();
		$this-&gt;fire();
	}
}</pre><p>There we go: cleaner, and easier to debug!</p><h3><span>Step 13 -</span> Avoid Deep Nesting</h3><p>Too many levels of nesting makes code difficult to read and maintain. Consider the following:</p><pre class="brush: php; title: ; notranslate">function doSomething() {
    if ($someCondition) {
        if ($someOtherCondition) {
            if ($yetSomeOtherCondition) {
                doSomethingSpecial();
            }
            doSomethingElse();
        }
    }
}</pre><p>You can refer to Tip #10 to make this code easier to read by reversing some of the conditions.</p><pre class="brush: php; title: ; notranslate">function doSomething() {
    if (!$someCondition) {
        return false;
    }
    if (!$someOtherCondition) {
        return false;
    }
    if ($yetSomeOtherCondition) {
        doSomethingSpecial();
    }
    doSomethingElse();
}</pre><p>This code is considerably cleaner and produces the same results as before.</p><p>When you find yourself with nested <code>if</code> statements, closely examine your code; your method may be performing more than one task. Here&#8217;s an example:</p><pre class="brush: php; title: ; notranslate">function someFunc() {
	if($oneThing) {
		$this-&gt;doSomething();
		if($anotherThing)
			$this-&gt;doSomethingElse();
	}
}</pre><p>In these cases, extract the nested methods into their own method:</p><pre class="brush: php; title: ; notranslate">function someFunc() {
	if($oneThing) {
		$this-&gt;doSomething();
		$this-&gt;doAnotherThing($anotherThing);
	}
}
private doAnotherThing($anotherThing) {
	if($anotherThing)
		$this-&gt;doSomethingElse();
}</pre><h3><span>Tip 14 &#8211; </span> Avoid Magic Numbers and Strings</h3><p>Magic numbers and strings are evil. Define variables or constants with the values you want to use in your code.</p><p>Instead of this:</p><pre class="brush: php; title: ; notranslate">function someFunct() {
	$this-&gt;order-&gt;set(23);
	$this-&gt;order-&gt;addProduct('superComputer');
	$this-&gt;shoppingList-&gt;add('superComputer');
}</pre><p>Specify what those numbers and strings mean, and assign them to a variable with a meaningful name, like this:</p><pre class="brush: php; title: ; notranslate">function someFunct() {
	$orderId = 23;
	$selectedProductName = 'superComputer';
	$this-&gt;order-&gt;set($orderId);
	$this-&gt;order-&gt;addProduct($selectedProductName);
	$this-&gt;shoppingList-&gt;add($selectedProductName);
}</pre><blockquote><p>While some might argue that we&#8217;re needlessly creating variables, the performance hit is negligible. Readability always takes priority. Remember: don&#8217;t optimize for performance until you can describe why it&#8217;s necessary.</p></blockquote><h3><span>Step 15 -</span> Use Built-In Array Functions</h3><p>Use the built-in array functions instead of <code>foreach()</code>.</p><p>Not Ideal:</p><pre class="brush: php; title: ; notranslate">foreach (&amp;$myArray as $key =&gt;$element) {
   if ($element &gt; 5) unset ($myArray[$key]);
}
</pre><p>Better:</p><pre class="brush: php; title: ; notranslate">$myArray = array_filter($myArray, function ($element) { return $element &lt;= 5;});
</pre><p>PHP offers a variety of array methods. They&#8217;re confusing at first, but take a day and try to learn as many as possible.</p><h3><span>Tip 16 -</span> Don&#8217;t Overuse Variables</h3><p>It&#8217;s easy to overuse variables, but remember that variables are stored in memory. For every variable you create, the system needs to allocate memory for that variable. Look at this code:</p><pre class="brush: php; title: ; notranslate">public function get_posts() {
	$query = $this-&gt;db-&gt;get('posts');
	$result = $query-&gt;result();
	return $result;
}</pre><p>The <code>$result</code> variable isn&#8217;t necessary. The following code omits that variable:</p><pre class="brush: php; title: ; notranslate">public function get_posts() {
	$query = $this-&gt;db-&gt;get('posts');
	return $query-&gt;result();
}
</pre><p>The difference is subtle, but we were able to improve this simple example. We kept the <i>$query</i> variable because it relates to the database, while <i>$result</i> related more to our logic.</p><hr
/><h2>General Programming Recommendations</h2><h3><span>Tip 17 -</span> Rely on the Database Engine</h3><blockquote
class="pullquote"><p>Anything less is a code smell.</p></blockquote><p>A database is designed for working with data; use its tools and abilities to make your application more efficient.</p><p>For example, you can avoid redundant database queries in many circumstances. Most plug-and-play user management scripts use two queries for user registration: one to check whether the e-mail/username already exists and another to actually add it to the database. A much better approach is to set the username field to <code>UNIQUE</code>. You can then use native MySQL functions to check whether or not the record was added to the database.</p><h3><span>Tip 18:</span> Properly Name Your Variables</h3><p>The days of naming your variables <code>x</code>, <code>y</code>, <code>z</code> are over (unless, of course, you&#8217;re dealing with a coordinate system). A variable represents an important part of your logic. Don&#8217;t want to type a long name? Get a better IDE. Modern IDEs auto-complete variable names in a blink of an eye.</p><blockquote><p> Always be coding for six months from now. Are you certain that you&#8217;ll remember what that <code>$sut</code> variables refers to a year from now? Likely not: be descriptive. Anything less is a code smell.</p></blockquote><h3><span>Tip 19 -</span> Methods Represent Actions</h3><blockquote
class="pullquote"><p>Mistakes happen; the key is to learn from them.</p></blockquote><p>Name your methods with verbs representing the action they perform. The main concept is the exact opposite of the variable naming scheme. Use a short, but descriptive, name in a large scope (ie: public methods), and use a longer and more detailed name in a short scope (ie: private / protected methods). This helps make your code read like well written prose.</p><p>Also avoid any language other than English, when naming your methods. It&#8217;s annoying to read function names like 做些什麼() or делатьчтото() in your project. It may be impossible for other programmers to understand your intent. While it might seem arrogant, for better or worse, English is the adopted language of code. Try to use it, if we&#8217;re working on a large team.</p><h3><span>Tip 20:</span> Structure Recommendations</h3><p>Finally, code structure is just as important to readability and maintainability as anything else we&#8217;ve talked about today. Here are two recommendations:</p><ul><li>Indent with four or two space-width tabs. Anything more, such as eight spaces, is too much and will make your code difficult to read.</li><li>Set a reasonable line-width and respect it. Forty characters in a line? We&#8217;re not in the &#8217;70s any more; set your limit to 120 characters, put a mark on the screen, and force yourself or your IDE to respect that limit. 120 characters gives you a nice width without making you scroll.</li></ul><hr
/><h2>Conclusion</h2><blockquote><p>&#8220;I&#8217;ve never made a stupid programming mistake.&#8221; &#8212; No one, ever.</p></blockquote><p>Mistakes happen; the key is to learn from them. We at Nettuts+ have made, and will continue to make, mistakes. Our hope is that you learn from our mistakes so that you can avoid them in the future. But, to be honest, the best way to learn best practices is to make the mistakes yourself!</p><p>Thanks for reading!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/0/da"><img src="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/1/da"><img src="http://feedads.g.doubleclick.net/~a/STk9scYu1AW8zHpi1m669kdRLyc/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=beiX3jlVpNE:I5zwCQjpQGg:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=beiX3jlVpNE:I5zwCQjpQGg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=beiX3jlVpNE:I5zwCQjpQGg:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=beiX3jlVpNE:I5zwCQjpQGg:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/beiX3jlVpNE" height="1" width="1"/>";s:14:"date_timestamp";i:1352572471;}i:3;a:13:{s:5:"title";s:50:"Building Single Page Web Apps with Sinatra: Part 1";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/qTu8nI_75Hw/";s:8:"comments";s:109:"http://net.tutsplus.com/tutorials/javascript-ajax/building-single-page-web-apps-with-sinatra-part-1/#comments";s:7:"pubdate";s:31:"Thu, 08 Nov 2012 17:25:50 +0000";s:2:"dc";a:1:{s:7:"creator";s:16:"Jonathan Cutrell";}s:8:"category";s:45:"JavaScript & AJAXRubyTutorialsknockoutsinatra";s:4:"guid";s:32:"http://net.tutsplus.com/?p=27911";s:11:"description";s:22441:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27911&c=1630399351' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27911&c=1630399351' border='0' alt='' /></a><p>Have you ever wanted to learn how to build a single page app with Sinatra and Knockout.js? Well, today is the day you learn! In this first section of a two-part series, we&#8217;ll review the process fo building a single page to-do application where users can view their tasks, sort them, mark them as complete, delete them, search through them, and add new tasks.</p><p><span
id="more-27911"></span></p><hr
/><h2>What is Sinatra?</h2><p>According to their website:</p><blockquote><p>Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort.</p></blockquote><p>Sinatra allows you to do things, like:</p><pre class="brush: ruby; title: ; notranslate">get &quot;/task/new&quot; do
    erb :form
end
</pre><p>This is a route that handles GET requests for &#8220;/task/new&#8221; and renders an <code>erb</code> form named <code>form.erb</code>. We won&#8217;t be using Sinatra to render Ruby templates; instead, we&#8217;ll use it only to send JSON responses to our Knockout.js managed front end (and some utility functions from jQuery like <code>$.ajax</code>). We will be using erb only to render the main HTML file.</p><hr
/><h2>What is Knockout?</h2><p>Knockout is a Model-View-ViewModel (MVVM) JavaScript framework that allows you to keep your models in special &#8220;observable&#8221; objects. It also keeps your UI up to date, based on those observed objects.</p><pre class="brush: plain; title: ; notranslate">-ToDo/
 -app.rb
 -models.rb
--views/
  -index.erb
-- public /
--- scripts/
   - knockout.js
   - jquery.js
   - app.js
--- styles/
   - styles.css
</pre><p>Here is what you&#8217;ll be building:</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2149_singlesinatra/task_ko.jpg" /></div><p>We&#8217;ll get started by defining our model and then our CRUD actions in Sinatra. We&#8217;ll rely on <a
href="http://datamapper.org/" title="DataMapper">DataMapper</a> and <a
href="http://www.sqlite.org/" title="SQLite">SQLite</a> for persistent storage, but you can use any ORM that you prefer.</p><p>Let&#8217;s add a task model to the <code>models.rb</code> file:</p><pre class="brush: ruby; title: ; notranslate">    DataMapper.setup(:default, 'sqlite:///path/to/project.db')
    class Task
      include DataMapper::Resource
      property :id,             Serial
      property :complete,        Boolean
      property :description,    Text
      property :created_at,        DateTime
      property :updated_at,        DateTime
    end
    DataMapper.auto_upgrade!
</pre><p>This task model essentially consists of a few different properties that we want to manipulate in our to-do application.</p><p>Next, let&#8217;s write our Sinatra JSON server. In the <code>app.rb</code> file, we&#8217;ll start by requiring a few different modules:</p><pre class="brush: ruby; title: ; notranslate">    require 'rubygems'
    require 'sinatra'
    require 'data_mapper'
    require File.dirname(__FILE__) + '/models.rb'
    require 'json'
    require 'Date'
</pre><p>The next step is to define some global defaults; in particular, we need a MIME type sent with each of our response headers to specify that every response is JSON.</p><pre class="brush: ruby; title: ; notranslate">before do
    content_type 'application/json'
end
</pre><p>The <code>before</code> helper function runs before every route match. You can also specify matching routes after <code>before</code>; if you, for instance, wanted to only run JSON responses if the URL ended in &#8220;.json&#8221;, you would use this:</p><pre class="brush: ruby; title: ; notranslate">before %r{.+\.json$} do
    content_type 'application/json'
end
</pre><p>Next, we define our CRUD routes, as well as one route to serve our <code>index.erb</code> file:</p><pre class="brush: ruby; title: ; notranslate">
get &quot;/&quot; do
	content_type 'html'
	erb :index
end
get &quot;/tasks&quot; do
    @tasks = Task.all
    @tasks.to_json
end
post &quot;/tasks/new&quot; do
    @task = Task.new
    @task.complete = false
    @task.description = params[:description]
    @task.created_at = DateTime.now
    @task.updated_at = null
end
put &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    @task.complete = params[:complete]
    @task.description = params[:description]
    @task.updated_at = DateTime.now
    if @task.save
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
delete &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    if @task.destroy
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
</pre><p>So the <code>app.rb</code> file now looks like this:</p><pre class="brush: ruby; title: ; notranslate">
require 'rubygems'
require 'sinatra'
require 'data_mapper'
require File.dirname(__FILE__) + '/models.rb'
require 'json'
require 'Date'
before do
    content_type 'application/json'
end
get &quot;/&quot; do
	content_type 'html'
	erb :index
end
get &quot;/tasks&quot; do
    @tasks = Task.all
    @tasks.to_json
end
post &quot;/tasks/new&quot; do
    @task = Task.new
    @task.complete = false
    @task.description = params[:description]
    @task.created_at = DateTime.now
    @task.updated_at = null
    if @task.save
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
put &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    @task.complete = params[:complete]
    @task.description = params[:description]
    @task.updated_at = DateTime.now
    if @task.save
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
delete &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    if @task.destroy
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
</pre><p>Each of these routes maps to an action. There is only one view (the &#8220;all tasks&#8221; view) that houses every action. Remember: in Ruby, the final value returns implicitly. You can explicitly return early, but whatever content these routes return will be the response sent from the server.</p><hr
/><h2>Knockout: Models</h2><p>Next, we start by defining our models in Knockout. In <code>app.js</code>, place the following code:</p><pre class="brush: jscript; title: ; notranslate">
function Task(data) {
    this.description = ko.observable(data.description);
    this.complete = ko.observable(data.complete);
    this.created_at = ko.observable(data.created_at);
    this.updated_at = ko.observable(data.updated_at);
    this.id = ko.observable(data.id);
}
</pre><p>As you can see, these properties are directly mapped to our model in <code>models.rb</code>. A <code>ko.observable</code> keeps the value updated across the UI when it changes without having to rely on the server or on the DOM to keep track of its state.</p><p>Next, we will add a <code>TaskViewModel</code>.</p><pre class="brush: jscript; title: ; notranslate">
function TaskViewModel() {
    var t = this;
    t.tasks = ko.observableArray([]);
    $.getJSON(&quot;/tasks&quot;, function(raw) {
        var tasks = $.map(raw, function(item) { return new Task(item) });
        self.tasks(tasks);
    });
}
ko.applyBindings(new TaskListViewModel());
</pre><p>This is the start of what will be the meat of our application. We begin by creating a <code>TaskViewModel</code> constructor function; a new instance of this function is passed to the Knockout <code>applyBindings()</code> function at the end of our file.</p><p>Inside our <code>TaskViewModel</code> is an initial call to retrieve tasks from the database, via the &#8220;/tasks&#8221; url. These are then mapped into the <code>ko.observableArray</code>, which is set to <code>t.tasks</code>. This array is the heart of our application&#8217;s functionality.</p><p>So, now, we have a retrieval function that shows tasks. Let&#8217;s make a creation function, and then create our actual template view. Add the following code to the <code>TaskViewModel</code>:</p><pre class="brush: jscript; title: ; notranslate">
	t.newTaskDesc = ko.observable();
    t.addTask = function() {
        var newtask = new Task({ description: this.newTaskDesc() });
        $.getJSON(&quot;/getdate&quot;, function(data){
            newtask.created_at(data.date);
            newtask.updated_at(data.date);
            t.tasks.push(newtask);
            t.saveTask(newtask);
            t.newTaskDesc(&quot;&quot;);
        })
    };
    t.saveTask = function(task) {
        var t = ko.toJS(task);
        $.ajax({
             url: &quot;http://localhost:9393/tasks&quot;,
             type: &quot;POST&quot;,
             data: t
        }).done(function(data){
            task.id(data.task.id);
        });
    }
</pre><blockquote
class="pullquote"><p>Knockout provides a convenient iteration ability&#8230;</p></blockquote><p>First, we set <code>newTaskDesc</code> as an observable. This allows us to use an input field easily to type a task description. Next, we define our <code>addTask()</code> function, which adds a task to the <code>observableArray</code>; it calls the <code>saveTask()</code> function, passing in the new task object.</p><p>The <code>saveTask()</code> function is agnostic of what kind of save it performs. (Later, we use the <code>saveTask()</code> function to delete tasks or mark them as complete.) An important note here: we rely on a convenience function to grab the current timestamp. This will not be the <em>exact</em> timestamp saved into the database, but it provides some data to drop into the view.</p><p>The route is very simple:</p><pre class="brush: ruby; title: ; notranslate">get &quot;/getdate&quot; do
    {:date =&gt; DateTime.now}.to_json
end
</pre><p>It should also be noted that the task&#8217;s id is not set until the Ajax request completes, as we need to assign it based on the server&#8217;s response.</p><p>Let&#8217;s create the HTML that our newly created JavaScript controls. A large portion of this file comes from the HTML5 boilerplate index file. This goes into the <code>index.erb</code> file:</p><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE html &gt;
&lt;html&gt;
&lt;!--[if lt IE 7]&gt;      &lt;html class=&quot;no-js lt-ie9 lt-ie8 lt-ie7&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 7]&gt;         &lt;html class=&quot;no-js lt-ie9 lt-ie8&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 8]&gt;         &lt;html class=&quot;no-js lt-ie9&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if gt IE 8]&gt;&lt;!--&gt;  &lt;!--&lt;![endif]--&gt;
    &lt;body&gt;
        &lt;meta charset=&quot;utf-8&quot;&gt;
        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge,chrome=1&quot;&gt;
        &lt;title&gt;ToDo&lt;/title&gt;
        &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;
        &lt;!-- Place favicon.ico and apple-touch-icon.png in the root directory --&gt;
        &lt;link rel=&quot;stylesheet&quot; href=&quot;styles/styles.css&quot;&gt;
        &lt;script src=&quot;scripts/modernizr-2.6.2.min.js&quot;&gt;&lt;/script&gt;
        &lt;!--[if lt IE 7]&gt;
            &lt;p class=&quot;chromeframe&quot;&gt;You are using an outdated browser. &lt;a href=&quot;http://browsehappy.com/&quot;&gt;Upgrade your browser today&lt;/a&gt; or &lt;a href=&quot;http://www.google.com/chromeframe/?redirect=true&quot;&gt;install Google Chrome Frame&lt;/a&gt; to better experience this site.&lt;/p&gt;
        &lt;![endif]--&gt;
        &lt;!-- Add your site or application content here --&gt;
        &lt;div id=&quot;container&quot;&gt;
            &lt;section id=&quot;taskforms&quot; class=&quot;clearfix&quot;&gt;
                &lt;div id=&quot;newtaskform&quot; class=&quot;floatleft fifty&quot;&gt;
                    &lt;h2&gt;Create a New Task&lt;/h2&gt;
                    &lt;form id=&quot;addtask&quot;&gt;
                        &lt;input&gt;
                        &lt;input type=&quot;submit&quot;&gt;
                    &lt;/form&gt;
                &lt;/div&gt;
                &lt;div id=&quot;tasksearchform&quot; class=&quot;floatright fifty&quot;&gt;
                    &lt;h2&gt;Search Tasks&lt;/h2&gt;
                    &lt;form id=&quot;searchtask&quot;&gt;
                        &lt;input&gt;
                    &lt;/form&gt;
                &lt;/div&gt;
            &lt;/section&gt;
            &lt;section id=&quot;tasktable&quot;&gt;
                &lt;h2&gt;Incomplete Tasks remaining: &lt;span&gt;&lt;/span&gt;&lt;/h2&gt;
                &lt;a&gt;Delete All Complete Tasks&lt;/a&gt;
                &lt;table&gt;
                    &lt;tbody&gt;&lt;tr&gt;
                        &lt;th&gt;DB ID&lt;/th&gt;
                        &lt;th&gt;Description&lt;/th&gt;
                        &lt;th&gt;Date Added&lt;/th&gt;
                        &lt;th&gt;Date Modified&lt;/th&gt;
                        &lt;th&gt;Complete?&lt;/th&gt;
                        &lt;th&gt;Delete&lt;/th&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;input type=&quot;checkbox&quot;&gt; &lt;/td&gt;
                        &lt;td class=&quot;destroytask&quot;&gt;&lt;a&gt;X&lt;/a&gt;&lt;/td&gt;
                    &lt;/tr&gt;
                &lt;/tbody&gt;&lt;/table&gt;
            &lt;/section&gt;
        &lt;/div&gt;
        &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js&quot;&gt;&lt;/script&gt;
        &lt;script&gt;window.jQuery || document.write('&lt;script src=&quot;scripts/jquery.js&quot;&gt;&lt;\/script&gt;')&lt;/script&gt;
        &lt;script src=&quot;scripts/knockout.js&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;scripts/app.js&quot;&gt;&lt;/script&gt;
        &lt;!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --&gt;
        &lt;script&gt;
            var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
            (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
            g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
            s.parentNode.insertBefore(g,s)}(document,'script'));
        &lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>Let&#8217;s take this template and fill in the bindings that Knockout uses to keep the UI in sync. For this part, we cover the creation of To-Do items. In the part two, we will cover more advanced functionality (including searching, sorting, deleting, and marking as complete).</p><p>Before we move on, let&#8217;s give our page a little bit of style. Since this tutorial isn&#8217;t about CSS, we&#8217;ll just drop this in and move right along. The following code is inside the HTML5 Boilerplate CSS file, which includes a reset and a few other things.</p><pre class="brush: css; title: ; notranslate">
section {
    width: 800px;
    margin: 20px auto;
}
table {
    width: 100%;
}
th {
    cursor: pointer;
}
tr {
    border-bottom: 1px solid #ddd;
}
tr.complete, tr.complete:nth-child(odd) {
    background: #efffd7;
    color: #ddd;
}
tr:nth-child(odd) {
    background-color: #dedede;
}
td {
    padding: 10px 20px;
}
td.destroytask {
    background: #ffeaea;
    color: #943c3c;
    font-weight: bold;
    opacity: 0.4;
}
td.destroytask:hover {
    cursor: pointer;
    background: #ffacac;
    color: #792727;
    opacity: 1;
}
.fifty { width: 50%; }
input {
    background: #fefefe;
    box-shadow: inset 0 0 6px #aaa;
    padding: 6px;
    border: none;
    width: 90%;
    margin: 4px;
}
input:focus {
    outline: none;
    box-shadow: inset 0 0 6px rgb(17, 148, 211);
    -webkit-transition: 0.2s all;
    background: rgba(17, 148, 211, 0.05);
}
input[type=submit] {
    background-color: #1194d3;
    background-image: -webkit-gradient(linear, left top, left bottom, from(rgb(17, 148, 211)), to(rgb(59, 95, 142)));
    background-image: -webkit-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: -moz-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: -o-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: -ms-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#1194d3', EndColorStr='#3b5f8e');
    padding: 6px 9px;
    border-radius: 3px;
    color: #fff;
    text-shadow: 1px 1px 1px #0a3d52;
    border: none;
    width: 30%;
}
input[type=submit]:hover {
    background: #0a3d52;
}
.floatleft { float: left; }
.floatright { float: right; }
</pre><p>Add this code to your <code>styles.css</code> file.</p><p>Now, let&#8217;s cover the &#8220;new task&#8221; form. We will add <code>data-bind</code> attributes to the form to make the Knockout bindings work. The <code>data-bind</code> attribute is how Knockout keeps the UI in sync, and allows for event binding and other important functionality. Replace the &#8220;new task&#8221; form with the following code.</p><pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;newtaskform&quot; class=&quot;floatleft fifty&quot;&gt;
    &lt;h2&gt;Create a New Task&lt;/h2&gt;
    &lt;form id=&quot;addtask&quot; data-bind=&quot;submit: addTask&quot;&gt;
        &lt;input data-bind=&quot;value: newTaskDesc&quot;&gt;
        &lt;input type=&quot;submit&quot;&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre><p>We&#8217;ll step through these one by one. First, the form element has a binding for the <code>submit</code> event. When the form is submitted, the <code>addTask()</code> function defined on the <code>TaskViewModel</code> executes. The first input element (which is implicitly of type=&#8221;text&#8221;) contains the <code>value</code> of the <code>ko.observable newTaskDesc</code> that we defined earlier. Whatever is in this field when submitting the form becomes the Task&#8217;s <code>description</code> property.</p><p>So we have a way to add tasks, but we need to display those tasks. We also need to add each of the task&#8217;s properties. Let&#8217;s iterate over the tasks and add them into the table. Knockout provides a convenient iteration ability to facilitate this; define a comment block with the following syntax:</p><pre class="brush: xml; title: ; notranslate">
&lt;!-- ko foreach: tasks --&gt;
	&lt;td data-bind=&quot;text: id&quot;&gt;&lt;/td&gt;
	&lt;td data-bind=&quot;text: description&quot;&gt;&lt;/td&gt;
	&lt;td data-bind=&quot;text: created_at&quot;&gt;&lt;/td&gt;
	&lt;td data-bind=&quot;text: updated_at&quot;&gt;&lt;/td&gt;
	&lt;td&gt; &lt;input type=&quot;checkbox&quot;&gt;&lt;/td&gt;
	&lt;td&gt; &lt;a&gt;X&lt;/a&gt;&lt;/td&gt;
&lt;!-- /ko --&gt;
</pre><blockquote
class="pullquote"><p>In Ruby, the final value is returns implicitly.</p></blockquote><p>This uses Knockout&#8217;s iteration capability. Each task is specifically defined on the <code>TaskViewModel</code> (<code>t.tasks</code>), and it stays in sync across the UI. Each task&#8217;s ID is added only after we&#8217;ve finished the DB call (as there is no way to ensure that we have the correct ID from the database until it is written), but the interface does not need to reflect inconsistencies like these.</p><p>You should now be able to use <code>shotgun app.rb</code> (<code>gem install shotgun</code>) from your working directory and test your app in the browser at <a
href="http://localhost:9393">http://localhost:9393</a>. (Note: make sure you have <code>gem install</code>&#8216;d all of your dependencies/required libraries before you try to run your application.) You should be able to add tasks and see them immediately appear.</p><hr
/><h2>Until Part Two</h2><p>In this tutorial, you learned how to create a JSON interface with Sinatra, and subsequently how to mirror those models in Knockout.js. You also learned how to create bindings to keep our UI in sync with our data. In the next part of this tutorial, we will talk solely about Knockout, and explain how to create sorting, searching, and updating functionality.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/0/da"><img src="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/1/da"><img src="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=qTu8nI_75Hw:NyS8NnHEN6A:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=qTu8nI_75Hw:NyS8NnHEN6A:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=qTu8nI_75Hw:NyS8NnHEN6A:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/qTu8nI_75Hw" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:105:"http://net.tutsplus.com/tutorials/javascript-ajax/building-single-page-web-apps-with-sinatra-part-1/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"10";}s:10:"feedburner";a:1:{s:8:"origlink";s:100:"http://net.tutsplus.com/tutorials/javascript-ajax/building-single-page-web-apps-with-sinatra-part-1/";}s:7:"summary";s:22441:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27911&c=1630399351' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27911&c=1630399351' border='0' alt='' /></a><p>Have you ever wanted to learn how to build a single page app with Sinatra and Knockout.js? Well, today is the day you learn! In this first section of a two-part series, we&#8217;ll review the process fo building a single page to-do application where users can view their tasks, sort them, mark them as complete, delete them, search through them, and add new tasks.</p><p><span
id="more-27911"></span></p><hr
/><h2>What is Sinatra?</h2><p>According to their website:</p><blockquote><p>Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort.</p></blockquote><p>Sinatra allows you to do things, like:</p><pre class="brush: ruby; title: ; notranslate">get &quot;/task/new&quot; do
    erb :form
end
</pre><p>This is a route that handles GET requests for &#8220;/task/new&#8221; and renders an <code>erb</code> form named <code>form.erb</code>. We won&#8217;t be using Sinatra to render Ruby templates; instead, we&#8217;ll use it only to send JSON responses to our Knockout.js managed front end (and some utility functions from jQuery like <code>$.ajax</code>). We will be using erb only to render the main HTML file.</p><hr
/><h2>What is Knockout?</h2><p>Knockout is a Model-View-ViewModel (MVVM) JavaScript framework that allows you to keep your models in special &#8220;observable&#8221; objects. It also keeps your UI up to date, based on those observed objects.</p><pre class="brush: plain; title: ; notranslate">-ToDo/
 -app.rb
 -models.rb
--views/
  -index.erb
-- public /
--- scripts/
   - knockout.js
   - jquery.js
   - app.js
--- styles/
   - styles.css
</pre><p>Here is what you&#8217;ll be building:</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2149_singlesinatra/task_ko.jpg" /></div><p>We&#8217;ll get started by defining our model and then our CRUD actions in Sinatra. We&#8217;ll rely on <a
href="http://datamapper.org/" title="DataMapper">DataMapper</a> and <a
href="http://www.sqlite.org/" title="SQLite">SQLite</a> for persistent storage, but you can use any ORM that you prefer.</p><p>Let&#8217;s add a task model to the <code>models.rb</code> file:</p><pre class="brush: ruby; title: ; notranslate">    DataMapper.setup(:default, 'sqlite:///path/to/project.db')
    class Task
      include DataMapper::Resource
      property :id,             Serial
      property :complete,        Boolean
      property :description,    Text
      property :created_at,        DateTime
      property :updated_at,        DateTime
    end
    DataMapper.auto_upgrade!
</pre><p>This task model essentially consists of a few different properties that we want to manipulate in our to-do application.</p><p>Next, let&#8217;s write our Sinatra JSON server. In the <code>app.rb</code> file, we&#8217;ll start by requiring a few different modules:</p><pre class="brush: ruby; title: ; notranslate">    require 'rubygems'
    require 'sinatra'
    require 'data_mapper'
    require File.dirname(__FILE__) + '/models.rb'
    require 'json'
    require 'Date'
</pre><p>The next step is to define some global defaults; in particular, we need a MIME type sent with each of our response headers to specify that every response is JSON.</p><pre class="brush: ruby; title: ; notranslate">before do
    content_type 'application/json'
end
</pre><p>The <code>before</code> helper function runs before every route match. You can also specify matching routes after <code>before</code>; if you, for instance, wanted to only run JSON responses if the URL ended in &#8220;.json&#8221;, you would use this:</p><pre class="brush: ruby; title: ; notranslate">before %r{.+\.json$} do
    content_type 'application/json'
end
</pre><p>Next, we define our CRUD routes, as well as one route to serve our <code>index.erb</code> file:</p><pre class="brush: ruby; title: ; notranslate">
get &quot;/&quot; do
	content_type 'html'
	erb :index
end
get &quot;/tasks&quot; do
    @tasks = Task.all
    @tasks.to_json
end
post &quot;/tasks/new&quot; do
    @task = Task.new
    @task.complete = false
    @task.description = params[:description]
    @task.created_at = DateTime.now
    @task.updated_at = null
end
put &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    @task.complete = params[:complete]
    @task.description = params[:description]
    @task.updated_at = DateTime.now
    if @task.save
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
delete &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    if @task.destroy
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
</pre><p>So the <code>app.rb</code> file now looks like this:</p><pre class="brush: ruby; title: ; notranslate">
require 'rubygems'
require 'sinatra'
require 'data_mapper'
require File.dirname(__FILE__) + '/models.rb'
require 'json'
require 'Date'
before do
    content_type 'application/json'
end
get &quot;/&quot; do
	content_type 'html'
	erb :index
end
get &quot;/tasks&quot; do
    @tasks = Task.all
    @tasks.to_json
end
post &quot;/tasks/new&quot; do
    @task = Task.new
    @task.complete = false
    @task.description = params[:description]
    @task.created_at = DateTime.now
    @task.updated_at = null
    if @task.save
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
put &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    @task.complete = params[:complete]
    @task.description = params[:description]
    @task.updated_at = DateTime.now
    if @task.save
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
delete &quot;/tasks/:id&quot; do
    @task = Task.find(params[:id])
    if @task.destroy
        {:task =&gt; @task, :status =&gt; &quot;success&quot;}.to_json
    else
        {:task =&gt; @task, :status =&gt; &quot;failure&quot;}.to_json
    end
end
</pre><p>Each of these routes maps to an action. There is only one view (the &#8220;all tasks&#8221; view) that houses every action. Remember: in Ruby, the final value returns implicitly. You can explicitly return early, but whatever content these routes return will be the response sent from the server.</p><hr
/><h2>Knockout: Models</h2><p>Next, we start by defining our models in Knockout. In <code>app.js</code>, place the following code:</p><pre class="brush: jscript; title: ; notranslate">
function Task(data) {
    this.description = ko.observable(data.description);
    this.complete = ko.observable(data.complete);
    this.created_at = ko.observable(data.created_at);
    this.updated_at = ko.observable(data.updated_at);
    this.id = ko.observable(data.id);
}
</pre><p>As you can see, these properties are directly mapped to our model in <code>models.rb</code>. A <code>ko.observable</code> keeps the value updated across the UI when it changes without having to rely on the server or on the DOM to keep track of its state.</p><p>Next, we will add a <code>TaskViewModel</code>.</p><pre class="brush: jscript; title: ; notranslate">
function TaskViewModel() {
    var t = this;
    t.tasks = ko.observableArray([]);
    $.getJSON(&quot;/tasks&quot;, function(raw) {
        var tasks = $.map(raw, function(item) { return new Task(item) });
        self.tasks(tasks);
    });
}
ko.applyBindings(new TaskListViewModel());
</pre><p>This is the start of what will be the meat of our application. We begin by creating a <code>TaskViewModel</code> constructor function; a new instance of this function is passed to the Knockout <code>applyBindings()</code> function at the end of our file.</p><p>Inside our <code>TaskViewModel</code> is an initial call to retrieve tasks from the database, via the &#8220;/tasks&#8221; url. These are then mapped into the <code>ko.observableArray</code>, which is set to <code>t.tasks</code>. This array is the heart of our application&#8217;s functionality.</p><p>So, now, we have a retrieval function that shows tasks. Let&#8217;s make a creation function, and then create our actual template view. Add the following code to the <code>TaskViewModel</code>:</p><pre class="brush: jscript; title: ; notranslate">
	t.newTaskDesc = ko.observable();
    t.addTask = function() {
        var newtask = new Task({ description: this.newTaskDesc() });
        $.getJSON(&quot;/getdate&quot;, function(data){
            newtask.created_at(data.date);
            newtask.updated_at(data.date);
            t.tasks.push(newtask);
            t.saveTask(newtask);
            t.newTaskDesc(&quot;&quot;);
        })
    };
    t.saveTask = function(task) {
        var t = ko.toJS(task);
        $.ajax({
             url: &quot;http://localhost:9393/tasks&quot;,
             type: &quot;POST&quot;,
             data: t
        }).done(function(data){
            task.id(data.task.id);
        });
    }
</pre><blockquote
class="pullquote"><p>Knockout provides a convenient iteration ability&#8230;</p></blockquote><p>First, we set <code>newTaskDesc</code> as an observable. This allows us to use an input field easily to type a task description. Next, we define our <code>addTask()</code> function, which adds a task to the <code>observableArray</code>; it calls the <code>saveTask()</code> function, passing in the new task object.</p><p>The <code>saveTask()</code> function is agnostic of what kind of save it performs. (Later, we use the <code>saveTask()</code> function to delete tasks or mark them as complete.) An important note here: we rely on a convenience function to grab the current timestamp. This will not be the <em>exact</em> timestamp saved into the database, but it provides some data to drop into the view.</p><p>The route is very simple:</p><pre class="brush: ruby; title: ; notranslate">get &quot;/getdate&quot; do
    {:date =&gt; DateTime.now}.to_json
end
</pre><p>It should also be noted that the task&#8217;s id is not set until the Ajax request completes, as we need to assign it based on the server&#8217;s response.</p><p>Let&#8217;s create the HTML that our newly created JavaScript controls. A large portion of this file comes from the HTML5 boilerplate index file. This goes into the <code>index.erb</code> file:</p><pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE html &gt;
&lt;html&gt;
&lt;!--[if lt IE 7]&gt;      &lt;html class=&quot;no-js lt-ie9 lt-ie8 lt-ie7&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 7]&gt;         &lt;html class=&quot;no-js lt-ie9 lt-ie8&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 8]&gt;         &lt;html class=&quot;no-js lt-ie9&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if gt IE 8]&gt;&lt;!--&gt;  &lt;!--&lt;![endif]--&gt;
    &lt;body&gt;
        &lt;meta charset=&quot;utf-8&quot;&gt;
        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge,chrome=1&quot;&gt;
        &lt;title&gt;ToDo&lt;/title&gt;
        &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width&quot;&gt;
        &lt;!-- Place favicon.ico and apple-touch-icon.png in the root directory --&gt;
        &lt;link rel=&quot;stylesheet&quot; href=&quot;styles/styles.css&quot;&gt;
        &lt;script src=&quot;scripts/modernizr-2.6.2.min.js&quot;&gt;&lt;/script&gt;
        &lt;!--[if lt IE 7]&gt;
            &lt;p class=&quot;chromeframe&quot;&gt;You are using an outdated browser. &lt;a href=&quot;http://browsehappy.com/&quot;&gt;Upgrade your browser today&lt;/a&gt; or &lt;a href=&quot;http://www.google.com/chromeframe/?redirect=true&quot;&gt;install Google Chrome Frame&lt;/a&gt; to better experience this site.&lt;/p&gt;
        &lt;![endif]--&gt;
        &lt;!-- Add your site or application content here --&gt;
        &lt;div id=&quot;container&quot;&gt;
            &lt;section id=&quot;taskforms&quot; class=&quot;clearfix&quot;&gt;
                &lt;div id=&quot;newtaskform&quot; class=&quot;floatleft fifty&quot;&gt;
                    &lt;h2&gt;Create a New Task&lt;/h2&gt;
                    &lt;form id=&quot;addtask&quot;&gt;
                        &lt;input&gt;
                        &lt;input type=&quot;submit&quot;&gt;
                    &lt;/form&gt;
                &lt;/div&gt;
                &lt;div id=&quot;tasksearchform&quot; class=&quot;floatright fifty&quot;&gt;
                    &lt;h2&gt;Search Tasks&lt;/h2&gt;
                    &lt;form id=&quot;searchtask&quot;&gt;
                        &lt;input&gt;
                    &lt;/form&gt;
                &lt;/div&gt;
            &lt;/section&gt;
            &lt;section id=&quot;tasktable&quot;&gt;
                &lt;h2&gt;Incomplete Tasks remaining: &lt;span&gt;&lt;/span&gt;&lt;/h2&gt;
                &lt;a&gt;Delete All Complete Tasks&lt;/a&gt;
                &lt;table&gt;
                    &lt;tbody&gt;&lt;tr&gt;
                        &lt;th&gt;DB ID&lt;/th&gt;
                        &lt;th&gt;Description&lt;/th&gt;
                        &lt;th&gt;Date Added&lt;/th&gt;
                        &lt;th&gt;Date Modified&lt;/th&gt;
                        &lt;th&gt;Complete?&lt;/th&gt;
                        &lt;th&gt;Delete&lt;/th&gt;
                    &lt;/tr&gt;
                    &lt;tr&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;/td&gt;
                        &lt;td&gt;&lt;input type=&quot;checkbox&quot;&gt; &lt;/td&gt;
                        &lt;td class=&quot;destroytask&quot;&gt;&lt;a&gt;X&lt;/a&gt;&lt;/td&gt;
                    &lt;/tr&gt;
                &lt;/tbody&gt;&lt;/table&gt;
            &lt;/section&gt;
        &lt;/div&gt;
        &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js&quot;&gt;&lt;/script&gt;
        &lt;script&gt;window.jQuery || document.write('&lt;script src=&quot;scripts/jquery.js&quot;&gt;&lt;\/script&gt;')&lt;/script&gt;
        &lt;script src=&quot;scripts/knockout.js&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;scripts/app.js&quot;&gt;&lt;/script&gt;
        &lt;!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --&gt;
        &lt;script&gt;
            var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
            (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
            g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
            s.parentNode.insertBefore(g,s)}(document,'script'));
        &lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><p>Let&#8217;s take this template and fill in the bindings that Knockout uses to keep the UI in sync. For this part, we cover the creation of To-Do items. In the part two, we will cover more advanced functionality (including searching, sorting, deleting, and marking as complete).</p><p>Before we move on, let&#8217;s give our page a little bit of style. Since this tutorial isn&#8217;t about CSS, we&#8217;ll just drop this in and move right along. The following code is inside the HTML5 Boilerplate CSS file, which includes a reset and a few other things.</p><pre class="brush: css; title: ; notranslate">
section {
    width: 800px;
    margin: 20px auto;
}
table {
    width: 100%;
}
th {
    cursor: pointer;
}
tr {
    border-bottom: 1px solid #ddd;
}
tr.complete, tr.complete:nth-child(odd) {
    background: #efffd7;
    color: #ddd;
}
tr:nth-child(odd) {
    background-color: #dedede;
}
td {
    padding: 10px 20px;
}
td.destroytask {
    background: #ffeaea;
    color: #943c3c;
    font-weight: bold;
    opacity: 0.4;
}
td.destroytask:hover {
    cursor: pointer;
    background: #ffacac;
    color: #792727;
    opacity: 1;
}
.fifty { width: 50%; }
input {
    background: #fefefe;
    box-shadow: inset 0 0 6px #aaa;
    padding: 6px;
    border: none;
    width: 90%;
    margin: 4px;
}
input:focus {
    outline: none;
    box-shadow: inset 0 0 6px rgb(17, 148, 211);
    -webkit-transition: 0.2s all;
    background: rgba(17, 148, 211, 0.05);
}
input[type=submit] {
    background-color: #1194d3;
    background-image: -webkit-gradient(linear, left top, left bottom, from(rgb(17, 148, 211)), to(rgb(59, 95, 142)));
    background-image: -webkit-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: -moz-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: -o-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: -ms-linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    background-image: linear-gradient(top, rgb(17, 148, 211), rgb(59, 95, 142));
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#1194d3', EndColorStr='#3b5f8e');
    padding: 6px 9px;
    border-radius: 3px;
    color: #fff;
    text-shadow: 1px 1px 1px #0a3d52;
    border: none;
    width: 30%;
}
input[type=submit]:hover {
    background: #0a3d52;
}
.floatleft { float: left; }
.floatright { float: right; }
</pre><p>Add this code to your <code>styles.css</code> file.</p><p>Now, let&#8217;s cover the &#8220;new task&#8221; form. We will add <code>data-bind</code> attributes to the form to make the Knockout bindings work. The <code>data-bind</code> attribute is how Knockout keeps the UI in sync, and allows for event binding and other important functionality. Replace the &#8220;new task&#8221; form with the following code.</p><pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;newtaskform&quot; class=&quot;floatleft fifty&quot;&gt;
    &lt;h2&gt;Create a New Task&lt;/h2&gt;
    &lt;form id=&quot;addtask&quot; data-bind=&quot;submit: addTask&quot;&gt;
        &lt;input data-bind=&quot;value: newTaskDesc&quot;&gt;
        &lt;input type=&quot;submit&quot;&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre><p>We&#8217;ll step through these one by one. First, the form element has a binding for the <code>submit</code> event. When the form is submitted, the <code>addTask()</code> function defined on the <code>TaskViewModel</code> executes. The first input element (which is implicitly of type=&#8221;text&#8221;) contains the <code>value</code> of the <code>ko.observable newTaskDesc</code> that we defined earlier. Whatever is in this field when submitting the form becomes the Task&#8217;s <code>description</code> property.</p><p>So we have a way to add tasks, but we need to display those tasks. We also need to add each of the task&#8217;s properties. Let&#8217;s iterate over the tasks and add them into the table. Knockout provides a convenient iteration ability to facilitate this; define a comment block with the following syntax:</p><pre class="brush: xml; title: ; notranslate">
&lt;!-- ko foreach: tasks --&gt;
	&lt;td data-bind=&quot;text: id&quot;&gt;&lt;/td&gt;
	&lt;td data-bind=&quot;text: description&quot;&gt;&lt;/td&gt;
	&lt;td data-bind=&quot;text: created_at&quot;&gt;&lt;/td&gt;
	&lt;td data-bind=&quot;text: updated_at&quot;&gt;&lt;/td&gt;
	&lt;td&gt; &lt;input type=&quot;checkbox&quot;&gt;&lt;/td&gt;
	&lt;td&gt; &lt;a&gt;X&lt;/a&gt;&lt;/td&gt;
&lt;!-- /ko --&gt;
</pre><blockquote
class="pullquote"><p>In Ruby, the final value is returns implicitly.</p></blockquote><p>This uses Knockout&#8217;s iteration capability. Each task is specifically defined on the <code>TaskViewModel</code> (<code>t.tasks</code>), and it stays in sync across the UI. Each task&#8217;s ID is added only after we&#8217;ve finished the DB call (as there is no way to ensure that we have the correct ID from the database until it is written), but the interface does not need to reflect inconsistencies like these.</p><p>You should now be able to use <code>shotgun app.rb</code> (<code>gem install shotgun</code>) from your working directory and test your app in the browser at <a
href="http://localhost:9393">http://localhost:9393</a>. (Note: make sure you have <code>gem install</code>&#8216;d all of your dependencies/required libraries before you try to run your application.) You should be able to add tasks and see them immediately appear.</p><hr
/><h2>Until Part Two</h2><p>In this tutorial, you learned how to create a JSON interface with Sinatra, and subsequently how to mirror those models in Knockout.js. You also learned how to create bindings to keep our UI in sync with our data. In the next part of this tutorial, we will talk solely about Knockout, and explain how to create sorting, searching, and updating functionality.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/0/da"><img src="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/1/da"><img src="http://feedads.g.doubleclick.net/~a/yffGCCcpFCz756H1xpYjd0e8xD0/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=qTu8nI_75Hw:NyS8NnHEN6A:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=qTu8nI_75Hw:NyS8NnHEN6A:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=qTu8nI_75Hw:NyS8NnHEN6A:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=qTu8nI_75Hw:NyS8NnHEN6A:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/qTu8nI_75Hw" height="1" width="1"/>";s:14:"date_timestamp";i:1352395550;}i:4;a:13:{s:5:"title";s:62:"Announcing Crafttuts+: Teaching Everything Craft and Handmade!";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/H5kF28W45rU/";s:8:"comments";s:107:"http://net.tutsplus.com/articles/news/announcing-crafttuts-teaching-everything-craft-and-handmade/#comments";s:7:"pubdate";s:31:"Wed, 07 Nov 2012 19:56:06 +0000";s:2:"dc";a:1:{s:7:"creator";s:13:"Joel Bankhead";}s:8:"category";s:13:"Newscrafttuts";s:4:"guid";s:32:"http://net.tutsplus.com/?p=27959";s:11:"description";s:5790:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27959&c=484548882' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27959&c=484548882' border='0' alt='' /></a><p><strong>We&#8217;re excited to let you know about the latest addition to the Tuts+ family — <a
href="http://craft.tutsplus.com">Crafttuts+!</a></strong></p><p>Crafttuts+ is focused on teaching everything crafty — fundamental craft skills, decorations, ceramics, crochet, jewellery-making, embroidery, candles, paper-craft, knitting, woodwork, printmaking, as well as how to market, sell, and promote your craft work.</p><p>Whether you&#8217;ve never even wondered about your crafty side, or consider yourself an expert, we&#8217;ve got you covered! Keep reading to learn a little bit more about what we’ll be offering on the site&#8230;</p><p><span
id="more-27959"></span></p><hr
/><h2>It&#8217;s Craft, but Not as You Know It</h2><p>It&#8217;s probably simplest to explain what you <em>won&#8217;t</em> find on Crafttuts+. We won&#8217;t be publishing half-baked tutorials with poor photography, incoherent steps, and mediocre outcomes. Nor will you find the type of craft projects that your nan might be interested in&#8230;</p><p><img
src="http://crafttuts.s3.amazonaws.com/launch-images/montage.jpg" alt="" /></p><p><strong>Crafttuts+ is all about teaching you how to embark on exciting craft projects that you&#8217;ll be desperate to try out.</strong> We&#8217;ll be publishing amazingly high-quality, clear, and visually impressive tutorials that are simple to follow. As well as fun one-off projects, we&#8217;ll have several sessions that take you through the basics of different types of craft — so you&#8217;ll have a solid place to start learning techniques to build upon later.</p><p>We&#8217;ll be publishing a combination of step-by-step written tutorials and screencasts/video lessons. In most weeks we&#8217;ll be publishing 4-5 high quality tutorials, so make sure to subscribe/follow Crafttuts+ below so you don&#8217;t miss a thing!</p><hr
/><h2>Find Crafttuts+ on Pinterest</h2><p><img
style="float: right; margin: 0 0 20px 20px;" src="http://crafttuts.s3.amazonaws.com/launch-images/pinterest.jpg" alt="Craftuts+ on Pinterest" />We&#8217;ll be making the most of Pinterest, and carefully curating our own set of boards to keep track of our favourite crafty projects and inspiration.</p><p>As well as sharing our latest tutorials on there, we&#8217;ll be highlighting the work of our authors, favourite crafters, and much more!</p><p>Just click below to follow Crafttuts+ on Pinterest, and keep up-to-date with the site:</p><p><a
href="http://pinterest.com/crafttuts/"><img
src="https://s-passets-ec.pinimg.com/images/about/buttons/follow-me-on-pinterest-button.png" alt="Follow Me on Pinterest" width="169" height="28" /></a></p><hr
/><h2>Follow &amp; Subscribe</h2><p>Don&#8217;t forget to follow Crafttuts+ on Twitter, Pinterest, Facebook, and everywhere else! Here&#8217;s how to keep up to date with what&#8217;s going on:</p><ul><li><a
href="http://twitter.com/crafttuts">Follow @crafttuts on Twitter</a></li><li><a
href="http://facebook.com/crafttuts">Like Crafttuts+ on Facebook</a></li><li><a
href="http://pinterest.com/crafttuts/">Find Crafttuts+ on Pinterest</a></li><li><a
href="https://plus.google.com/116450899676482348348/posts">Find us on Google+</a></li><li><a
href="http://feeds.feedburner.com/Crafttuts">Subscribe via RSS</a></li><li><a
href="http://eepurl.com/pIedH">Join the Newsletter</a></li></ul><p>Thanks for being part of the site, and we hope you&#8217;ll enjoy all the crafty projects we have lined up over the coming weeks!</p><hr
/><h2>Win $300 in Our Pinterest Competition</h2><p>To celebrate the launch, we&#8217;re running a competition to win $300 to spend on craft supplies and goodies! Whether you’re in need of new crafty supplies, books, materials, or anything else, this is your chance to win a fantastic prize.</p><p><a
href="http://craft.tutsplus.com/articles/competitions/win-300-to-spend-on-craft-supplies-with-our-pinterest-competition/"><div
class="tutorial_image"><img
src="http://crafttuts.s3.amazonaws.com/launch-images/pinteresthowtoenter.jpg" alt="How to Enter" /></div><p></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/0/da"><img src="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/1/da"><img src="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=H5kF28W45rU:FqA57H-gVjI:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=H5kF28W45rU:FqA57H-gVjI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=H5kF28W45rU:FqA57H-gVjI:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/H5kF28W45rU" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:103:"http://net.tutsplus.com/articles/news/announcing-crafttuts-teaching-everything-craft-and-handmade/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"21";}s:10:"feedburner";a:1:{s:8:"origlink";s:98:"http://net.tutsplus.com/articles/news/announcing-crafttuts-teaching-everything-craft-and-handmade/";}s:7:"summary";s:5790:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27959&c=484548882' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27959&c=484548882' border='0' alt='' /></a><p><strong>We&#8217;re excited to let you know about the latest addition to the Tuts+ family — <a
href="http://craft.tutsplus.com">Crafttuts+!</a></strong></p><p>Crafttuts+ is focused on teaching everything crafty — fundamental craft skills, decorations, ceramics, crochet, jewellery-making, embroidery, candles, paper-craft, knitting, woodwork, printmaking, as well as how to market, sell, and promote your craft work.</p><p>Whether you&#8217;ve never even wondered about your crafty side, or consider yourself an expert, we&#8217;ve got you covered! Keep reading to learn a little bit more about what we’ll be offering on the site&#8230;</p><p><span
id="more-27959"></span></p><hr
/><h2>It&#8217;s Craft, but Not as You Know It</h2><p>It&#8217;s probably simplest to explain what you <em>won&#8217;t</em> find on Crafttuts+. We won&#8217;t be publishing half-baked tutorials with poor photography, incoherent steps, and mediocre outcomes. Nor will you find the type of craft projects that your nan might be interested in&#8230;</p><p><img
src="http://crafttuts.s3.amazonaws.com/launch-images/montage.jpg" alt="" /></p><p><strong>Crafttuts+ is all about teaching you how to embark on exciting craft projects that you&#8217;ll be desperate to try out.</strong> We&#8217;ll be publishing amazingly high-quality, clear, and visually impressive tutorials that are simple to follow. As well as fun one-off projects, we&#8217;ll have several sessions that take you through the basics of different types of craft — so you&#8217;ll have a solid place to start learning techniques to build upon later.</p><p>We&#8217;ll be publishing a combination of step-by-step written tutorials and screencasts/video lessons. In most weeks we&#8217;ll be publishing 4-5 high quality tutorials, so make sure to subscribe/follow Crafttuts+ below so you don&#8217;t miss a thing!</p><hr
/><h2>Find Crafttuts+ on Pinterest</h2><p><img
style="float: right; margin: 0 0 20px 20px;" src="http://crafttuts.s3.amazonaws.com/launch-images/pinterest.jpg" alt="Craftuts+ on Pinterest" />We&#8217;ll be making the most of Pinterest, and carefully curating our own set of boards to keep track of our favourite crafty projects and inspiration.</p><p>As well as sharing our latest tutorials on there, we&#8217;ll be highlighting the work of our authors, favourite crafters, and much more!</p><p>Just click below to follow Crafttuts+ on Pinterest, and keep up-to-date with the site:</p><p><a
href="http://pinterest.com/crafttuts/"><img
src="https://s-passets-ec.pinimg.com/images/about/buttons/follow-me-on-pinterest-button.png" alt="Follow Me on Pinterest" width="169" height="28" /></a></p><hr
/><h2>Follow &amp; Subscribe</h2><p>Don&#8217;t forget to follow Crafttuts+ on Twitter, Pinterest, Facebook, and everywhere else! Here&#8217;s how to keep up to date with what&#8217;s going on:</p><ul><li><a
href="http://twitter.com/crafttuts">Follow @crafttuts on Twitter</a></li><li><a
href="http://facebook.com/crafttuts">Like Crafttuts+ on Facebook</a></li><li><a
href="http://pinterest.com/crafttuts/">Find Crafttuts+ on Pinterest</a></li><li><a
href="https://plus.google.com/116450899676482348348/posts">Find us on Google+</a></li><li><a
href="http://feeds.feedburner.com/Crafttuts">Subscribe via RSS</a></li><li><a
href="http://eepurl.com/pIedH">Join the Newsletter</a></li></ul><p>Thanks for being part of the site, and we hope you&#8217;ll enjoy all the crafty projects we have lined up over the coming weeks!</p><hr
/><h2>Win $300 in Our Pinterest Competition</h2><p>To celebrate the launch, we&#8217;re running a competition to win $300 to spend on craft supplies and goodies! Whether you’re in need of new crafty supplies, books, materials, or anything else, this is your chance to win a fantastic prize.</p><p><a
href="http://craft.tutsplus.com/articles/competitions/win-300-to-spend-on-craft-supplies-with-our-pinterest-competition/"><div
class="tutorial_image"><img
src="http://crafttuts.s3.amazonaws.com/launch-images/pinteresthowtoenter.jpg" alt="How to Enter" /></div><p></a></p>
<p><a href="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/0/da"><img src="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/1/da"><img src="http://feedads.g.doubleclick.net/~a/-7LSbNvdIWF2Dth-y0yqtw7tDCc/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=H5kF28W45rU:FqA57H-gVjI:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=H5kF28W45rU:FqA57H-gVjI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=H5kF28W45rU:FqA57H-gVjI:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=H5kF28W45rU:FqA57H-gVjI:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/H5kF28W45rU" height="1" width="1"/>";s:14:"date_timestamp";i:1352318166;}i:5;a:13:{s:5:"title";s:35:"The Latest Updates to jQuery Mobile";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/05Uf-v1kENc/";s:8:"comments";s:95:"http://net.tutsplus.com/tutorials/javascript-ajax/the-latest-updates-to-jquery-mobile/#comments";s:7:"pubdate";s:31:"Tue, 06 Nov 2012 15:04:01 +0000";s:2:"dc";a:1:{s:7:"creator";s:13:"Andy Matthews";}s:8:"category";s:30:"JavaScript & AJAXjquery mobile";s:4:"guid";s:32:"http://net.tutsplus.com/?p=27941";s:11:"description";s:20351:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27941&c=1333153545' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27941&c=1333153545' border='0' alt='' /></a><p>Not too long ago, the jQuery team released <a
href="http://jquerymobile.com">jQuery Mobile 1.2</a>. This new release has some fantastic changes! In this article, we&#39;re going to review some of the new widgets available to developers, take a look at changes made to existing widgets, and glance over a few impactful enhancements that could affect your jQuery Mobile application. Let&#39;s get started, shall we?</p><p><span
id="more-27941"></span></p><p>Firstly, we&#39;ll need to download the bits and bytes. Head over to the <a
href="http://jquerymobile.com/download/">jQuery Mobile download page</a> and download the option that best meets your needs. Alternately you can just use the boilerplate code provided below.</p><p>Additionally, now might be a good time to quickly discuss the <a
href="http://jquerymobile.com/download-builder/">Download Builder</a> that the jQuery Mobile team is building. It&#39;s still in Alpha, but it allows you to customize your download to include only the parts of jQuery Mobile that you require, and nothing more. You can exclude specific events, transitions, form elements, or widgets that you don&#39;t care about. It&#39;s meant for the developers who are ultra-concerned with grasping the highest level of performance out of his or her application.</p><hr
/><h2>Widgets</h2><p>The beating heart of any jQuery Mobile application are its widgets. Arguably they&#39;re the most visible part of the page, and the part that allows users to interact with the page in such an easy manner. The jQuery Mobile team has spent countless hours testing, building, and refining their widgets to make sure that they&#39;re the best they can be. In version 1.2, the team has really knocked it out of the park with a widget that developers have been asking for since the framework was first released: popup modals.</p><h3>Popups</h3><p>A popup modal is a small section of the page that overlays other parts of the page. They&#39;re most typically used as tooltips, or to display photos, maps, and additional content. This information is usually not important enough to warrant another page, but is still important to need displaying by itself. The way jQuery Mobile 1.2 has implemented popups is perfect. Let&#39;s learn how easy it is to add popups to a project.</p><p>A quick note, for the sake of brevity: all of the code samples below will use the following boilerplate HTML. The jQuery Mobile CSS and JS files (including jQuery) are hotlinked using the jQuery CDN for your convenience.</p><pre class="brush: xml; title: ; notranslate">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
    &lt;title&gt;jQuery Mobile 1.2&lt;/title&gt;
    &lt;link rel=&quot;stylesheet&quot;  href=&quot;http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css&quot; /&gt;
    &lt;script src=&quot;http://code.jquery.com/jquery-1.8.0.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div data-role=&quot;content&quot;&gt;
        &lt;!-- your content goes here --&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>Adding a popup to a page in your application is a two-step process. First you&#39;ll need some means of triggering the popup. This is generally a link, or button, or something the user interacts with. To trigger element, we add the following attribute:</p><pre class="brush: jscript; title: ; notranslate">data-rel=&quot;popup&quot;
</pre><p>Second, you need the content to be displayed. This could range from a single <code>div</code> to a <code>menu</code>, a <code>form</code>, or even photos. The content element gets its own attribute:</p><pre class="brush: jscript; title: ; notranslate">data-role=&quot;popup&quot;
</pre><p>Finally, for simple link buttons, the <code>href</code> attribute must correspond to the <code>id</code> of the content to be displayed. Let&#39;s review the complete implementation.</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#simplepopup&quot; data-rel=&quot;popup&quot;&gt;Open Popup&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;simplepopup&quot;&gt;
    &lt;p&gt;This is a completely basic popup, no options set.&lt;p&gt;
&lt;/div&gt;
</pre><p>What you&#39;ll see on the page should look something similar to this:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-simple.png' alt='Simple popup' title='' border='0'></div><h4>Tooltips</h4><p>Now that you know how to create a popup, let&#39;s look at other possibilities. One common use is a tooltip; help text or expanded text shown when a user clicks on a button. Set up the code the same as before:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#tooltip&quot; data-rel=&quot;popup&quot; data-role=&quot;button&quot;&gt;Find out more&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;tooltip&quot; data-theme=&quot;e&quot;&gt;
    &lt;p&gt;You found out more!.&lt;/p&gt;
&lt;/div&gt;
</pre><p>This time, we&#39;re styling the resulting content using the <strong>e</strong> swatch from jQuery Mobile to give it a more pleasant appearance. This helps us remember that popups are first class jQuery Mobile citizens, and can be treated just like anything else on the page.</p><h4>Menus</h4><p>Let&#39;s move on to something a bit more complicated: a menu. That&#39;s a popular approach to page navigation. Give the user the a menu right at their fingertips. So what does that look like with popups?</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#menu&quot; data-rel=&quot;popup&quot; data-role=&quot;button&quot;&gt;Menu&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;menu&quot; data-theme=&quot;a&quot;&gt;
    &lt;ul data-role=&quot;listview&quot; data-theme=&quot;c&quot; data-inset=&quot;true&quot;&gt;
        &lt;li data-role=&quot;divider&quot; data-theme=&quot;a&quot;&gt;My Menu&lt;/li&gt;
        &lt;li&gt;Unlinked&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;methods.html&quot;&gt;Linked&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;methods.html&quot;&gt;With count&lt;/a&gt;&lt;span class=&quot;ui-li-count&quot;&gt;42&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;
</pre><p>And the resulting output should resemble this:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popups-menu.png' alt='Popup menu' title='' border='0'></div><p>You can also use 1.2&#39;s collapsible lists in popups. Here&#39;s a quick example:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#nestedmenu&quot; data-rel=&quot;popup&quot; data-role=&quot;button&quot;&gt;Nested Menu&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;nestedmenu&quot; data-theme=&quot;none&quot;&gt;
    &lt;div data-role=&quot;collapsible-set&quot; data-theme=&quot;b&quot; data-content-theme=&quot;c&quot; data-collapsed-icon=&quot;arrow-r&quot; data-expanded-icon=&quot;arrow-d&quot; style=&quot;margin:0; width:250px;&quot;&gt;
        &lt;div data-role=&quot;collapsible&quot; data-inset=&quot;false&quot;&gt;
            &lt;h2&gt;Colors&lt;/h2&gt;
            &lt;ul data-role=&quot;listview&quot;&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Red&lt;/a&gt;&lt;/li&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Blue&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
        &lt;div data-role=&quot;collapsible&quot; data-inset=&quot;false&quot;&gt;
            &lt;h2&gt;Shapes&lt;/h2&gt;
            &lt;ul data-role=&quot;listview&quot;&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Circle&lt;/a&gt;&lt;/li&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Square&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre><p>And the results:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popups-nested-menu.png' alt='Popup menu' title='' border='0'></div><p>It&#39;s worth noting that <strong>data-inset=&quot;true&quot;</strong> is required on the <code>listview</code> or the corners of your list will show up. Try and you&#39;ll see.</p><h4>Forms</h4><p>Another popular UX approach is to show a login form hovering over the top of a page. That&#39;s now possible with jQuery Mobile popups. Here&#39;s a simple username/password form.</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#login&quot; data-rel=&quot;popup&quot; data-position-to=&quot;window&quot; data-role=&quot;button&quot;&gt;Login&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;login&quot; data-theme=&quot;a&quot;&gt;
    &lt;form style=&quot;padding:10px 20px;&quot;&gt;
        &lt;h3&gt;Please sign in&lt;/h3&gt;
        &lt;label for=&quot;un&quot; class=&quot;ui-hidden-accessible&quot;&gt;Username:&lt;/label&gt;
        &lt;input type=&quot;js&quot; name=&quot;user&quot; id=&quot;un&quot; placeholder=&quot;username&quot; /&gt;
        &lt;label for=&quot;pw&quot; class=&quot;ui-hidden-accessible&quot;&gt;Password:&lt;/label&gt;
        &lt;input type=&quot;password&quot; name=&quot;pass&quot; id=&quot;pw&quot; placeholder=&quot;password&quot; /&gt;
        &lt;button type=&quot;submit&quot; data-theme=&quot;b&quot;&gt;Sign in&lt;/button&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre><p>Which gives you:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-form.png' alt='Popup menu' title='' border='0'></div><p>By default, popups center themselves over the object which triggered them. There&#39;s an optional attribute which you&#39;ll see in the next three examples. It&#39;s <strong>data-position-to=&quot;window&quot;</strong> and you apply it to the element which triggers the popup. Try adding that to the <strong>Login</strong> button above to see what happens.</p><h4>Dialogs</h4><p>A common need for web applications is the ability to interact with the user. We just reviewed one approach: a login form. But, sometimes, you need to prompt the user with questions. A dialog is a perfect solution for this; and what do you know, popups have you covered! So what does that code look like? Here&#39;s a simple example:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#dialog&quot; data-rel=&quot;popup&quot; data-position-to=&quot;window&quot; data-role=&quot;button&quot; data-transition=&quot;pop&quot;&gt;Dialog&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;dialog&quot; data-overlay-theme=&quot;a&quot; data-theme=&quot;c&quot;&gt;
    &lt;div data-role=&quot;header&quot; data-theme=&quot;a&quot;&gt;
        &lt;h1&gt;Delete Page?&lt;/h1&gt;
    &lt;/div&gt;
    &lt;div data-role=&quot;content&quot; data-theme=&quot;d&quot;&gt;
        &lt;h3&gt;Are you sure you want to delete this page?&lt;/h3&gt;
        &lt;p&gt;This action cannot be undone.&lt;/p&gt;
        &lt;a href=&quot;#&quot; data-role=&quot;button&quot; data-inline=&quot;true&quot; data-rel=&quot;back&quot; data-theme=&quot;c&quot;&gt;No&lt;/a&gt;
        &lt;a href=&quot;#&quot; data-role=&quot;button&quot; data-inline=&quot;true&quot; data-rel=&quot;back&quot; data-theme=&quot;b&quot;&gt;Yes, Delete it&lt;/a&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-dialog.png' alt='Popup menu' title='' border='0'></div><p>In the popup content container, note another new attribute for your use: <strong>data-overlay-theme=&quot;a&quot;</strong>. This attribute is what applies the shaded background to the dialog box. It&#39;s affected by your theme, so be careful when working with themes created with <a
href="http://jqueryui.com/themeroller/">ThemeRoller</a>.</p><h4>Photos</h4><p>I can&#39;t count the number of times I&#39;ve seen jQuery Mobile developers ask for some better way of handling image galleries. While popups aren&#39;t the perfect solution for large numbers of images, they&#39;re great for a handful of images that need to be viewed larger. Even better, it&#8217;s incredibly easy; check it out:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#photo&quot; data-rel=&quot;popup&quot; data-position-to=&quot;window&quot; data-role=&quot;button&quot; data-transition=&quot;fade&quot;&gt;Photo&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;photo&quot; data-overlay-theme=&quot;a&quot; data-theme=&quot;d&quot; data-corners=&quot;false&quot;&gt;
    &lt;a href=&quot;#&quot; data-rel=&quot;back&quot; data-role=&quot;button&quot; data-theme=&quot;a&quot; data-icon=&quot;delete&quot; data-iconpos=&quot;nojs&quot; class=&quot;ui-btn-right&quot;&gt;Close&lt;/a&gt;&lt;img src=&quot;http://lorempixel.com/450/300/food/&quot; /&gt;
&lt;/div&gt;
</pre><p>The above code gives you an elegant photo centered to the window, including a close window button.</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-photo.png' alt='Popup menu' title='' border='0'></div><p>How did they do that? Within the context of a popup, the <code>anchor</code> tag has attributes which behave slightly different than when used in other locations on the page. Specifically, the <strong>ui-btn-right</strong> class positions the image in the corner of the image rather than the side, while the <strong>data-icon</strong> and <strong>data-iconpos</strong> attributes allow you to style the button just as you would a regular button.</p><p>You can get pretty fancy with popups including, but not limited to, displaying inline video and even interactive maps. Check the <a
href="http://jquerymobile.com/demos/1.2.0/docs/pages/popup/popup-iframes.html">jQuery Mobile documentation for popups and iframes</a>.</p><h3>Collapsible List Views</h3><p>Another great new feature is the ability to combine collapsible sets with list views. Call &#39;em &#8220;Collapsible List Views&#8221; and you&#39;ve got a brand new widget in jQuery Mobile 1.2. How do they work? I&#39;m glad you asked. Simply create any list you like, then wrap it in a collapsible set. Collapsible List Views also support multiple lists &#8211; so get crazy!</p><pre class="brush: xml; title: ; notranslate">&lt;div data-role=&quot;collapsible&quot; data-theme=&quot;b&quot; data-content-theme=&quot;c&quot;&gt;
    &lt;h2&gt;Favorite Spice Girl?&lt;/h2&gt;
    &lt;ul data-role=&quot;listview&quot;&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Posh&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Scary&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Sporty&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Baby&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Ginger&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;
</pre><p>The code above would result in this Collapsible List View:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/listview-collapsible.png' alt='Popup menu' title='' border='0'></div><hr
/><h2>Enhancements</h2><p>In addition to new widget types, jQuery Mobile 1.2 provides a number of useful enhancements to existing functionality. Let&#39;s take a look at some of the more valuable ones.</p><h3>jQuery Support Changes</h3><p>One of the biggest enhancements made in version 1.2 is the added support for jQuery 1.8. This brings some significant performance increases in the form of a completely rewritten Sizzle.js (the selector engine for jQuery), along with numerous other improvements.</p><p>The tradeoff is that the jQuery Mobile team decided that it was time to sunset support for jQuery 1.6. This may be unfortunate  for some folks out there who are still using older versions of jQuery, but it&#8217;s a fair trade.</p><h3>List View Autodividers</h3><p>If you&#39;ve ever had to manage a list of constantly changing people, places, or things in jQuery Mobile then, you&#39;ve probably had to write some tricky code to display dynamic listview headers. Bummer that you spent all that time, because the jQuery Mobile team made it as easy as dropping in a single attribute.</p><pre class="brush: jscript; title: ; notranslate">data-autodividers=&quot;true&quot;
</pre><p>That turns this list:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/listview-dividers-before.png' alt='Popup menu' title='' border='0'></div><p>Into:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/listview-dividers-after.png' alt='Popup menu' title='' border='0'></div><p>Note that this does not manage sorting, grouping, or filtering. For that sort of functionality, consider trying my <a
href="http://andymatthews.net/code/jqm-tinysort/">jQuery Mobile Tinysort plugin</a>.</p><h3>Read-Only Lists</h3><p>jQuery Mobile offers &quot;read-only&quot; list views, but it was difficult to tell that they weren&#39;t clickable. Version 1.2 removes the list gradient, making the row a flat color. This should provide a better visual cue to your users.</p><h3>Better Width adjustments on Form Elements</h3><p>Version 1.2 fixes a semi-annoying issue with form elements, whereby they wouldn&#39;t take up the full width of their parent element in some cases.</p><h3>Additional Devices Added</h3><p>You might have noticed that new devices are being added almost on a daily basis. The jQuery Mobile team does their best to test against as many of these devices as possible. Newly added to the A grade platform list are the following devices/operating systems/browsers: iOS 6, Android 4.1 (Jellybean), Tizen, Firefox for Android, and Kindle Fire HD.</p><hr
/><h2>Full List of Changes</h2><p>You can find a complete list of the changes made for version 1.2 on the <a
href="http://jquerymobile.com/blog/2012/10/02/announcing-jquery-mobile-1-2-0-final/#changelog">jQuery Mobile blog</a>.</p><p>I hope that some of these improvements will help to improve your applications. Remember that the jQuery Mobile team is on your side! If you see something that you think would be valuable, ask for it: create an issue in <a
href="https://github.com/jquery/jquery-mobile">their Github repository</a>, and suggest it. Better yet, fork their repo and add some code yourself!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/0/da"><img src="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/1/da"><img src="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=05Uf-v1kENc:lJNanzsjGks:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=05Uf-v1kENc:lJNanzsjGks:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=05Uf-v1kENc:lJNanzsjGks:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/05Uf-v1kENc" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:91:"http://net.tutsplus.com/tutorials/javascript-ajax/the-latest-updates-to-jquery-mobile/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"14";}s:10:"feedburner";a:1:{s:8:"origlink";s:86:"http://net.tutsplus.com/tutorials/javascript-ajax/the-latest-updates-to-jquery-mobile/";}s:7:"summary";s:20351:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27941&c=1333153545' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27941&c=1333153545' border='0' alt='' /></a><p>Not too long ago, the jQuery team released <a
href="http://jquerymobile.com">jQuery Mobile 1.2</a>. This new release has some fantastic changes! In this article, we&#39;re going to review some of the new widgets available to developers, take a look at changes made to existing widgets, and glance over a few impactful enhancements that could affect your jQuery Mobile application. Let&#39;s get started, shall we?</p><p><span
id="more-27941"></span></p><p>Firstly, we&#39;ll need to download the bits and bytes. Head over to the <a
href="http://jquerymobile.com/download/">jQuery Mobile download page</a> and download the option that best meets your needs. Alternately you can just use the boilerplate code provided below.</p><p>Additionally, now might be a good time to quickly discuss the <a
href="http://jquerymobile.com/download-builder/">Download Builder</a> that the jQuery Mobile team is building. It&#39;s still in Alpha, but it allows you to customize your download to include only the parts of jQuery Mobile that you require, and nothing more. You can exclude specific events, transitions, form elements, or widgets that you don&#39;t care about. It&#39;s meant for the developers who are ultra-concerned with grasping the highest level of performance out of his or her application.</p><hr
/><h2>Widgets</h2><p>The beating heart of any jQuery Mobile application are its widgets. Arguably they&#39;re the most visible part of the page, and the part that allows users to interact with the page in such an easy manner. The jQuery Mobile team has spent countless hours testing, building, and refining their widgets to make sure that they&#39;re the best they can be. In version 1.2, the team has really knocked it out of the park with a widget that developers have been asking for since the framework was first released: popup modals.</p><h3>Popups</h3><p>A popup modal is a small section of the page that overlays other parts of the page. They&#39;re most typically used as tooltips, or to display photos, maps, and additional content. This information is usually not important enough to warrant another page, but is still important to need displaying by itself. The way jQuery Mobile 1.2 has implemented popups is perfect. Let&#39;s learn how easy it is to add popups to a project.</p><p>A quick note, for the sake of brevity: all of the code samples below will use the following boilerplate HTML. The jQuery Mobile CSS and JS files (including jQuery) are hotlinked using the jQuery CDN for your convenience.</p><pre class="brush: xml; title: ; notranslate">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
    &lt;title&gt;jQuery Mobile 1.2&lt;/title&gt;
    &lt;link rel=&quot;stylesheet&quot;  href=&quot;http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css&quot; /&gt;
    &lt;script src=&quot;http://code.jquery.com/jquery-1.8.0.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div data-role=&quot;content&quot;&gt;
        &lt;!-- your content goes here --&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>Adding a popup to a page in your application is a two-step process. First you&#39;ll need some means of triggering the popup. This is generally a link, or button, or something the user interacts with. To trigger element, we add the following attribute:</p><pre class="brush: jscript; title: ; notranslate">data-rel=&quot;popup&quot;
</pre><p>Second, you need the content to be displayed. This could range from a single <code>div</code> to a <code>menu</code>, a <code>form</code>, or even photos. The content element gets its own attribute:</p><pre class="brush: jscript; title: ; notranslate">data-role=&quot;popup&quot;
</pre><p>Finally, for simple link buttons, the <code>href</code> attribute must correspond to the <code>id</code> of the content to be displayed. Let&#39;s review the complete implementation.</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#simplepopup&quot; data-rel=&quot;popup&quot;&gt;Open Popup&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;simplepopup&quot;&gt;
    &lt;p&gt;This is a completely basic popup, no options set.&lt;p&gt;
&lt;/div&gt;
</pre><p>What you&#39;ll see on the page should look something similar to this:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-simple.png' alt='Simple popup' title='' border='0'></div><h4>Tooltips</h4><p>Now that you know how to create a popup, let&#39;s look at other possibilities. One common use is a tooltip; help text or expanded text shown when a user clicks on a button. Set up the code the same as before:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#tooltip&quot; data-rel=&quot;popup&quot; data-role=&quot;button&quot;&gt;Find out more&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;tooltip&quot; data-theme=&quot;e&quot;&gt;
    &lt;p&gt;You found out more!.&lt;/p&gt;
&lt;/div&gt;
</pre><p>This time, we&#39;re styling the resulting content using the <strong>e</strong> swatch from jQuery Mobile to give it a more pleasant appearance. This helps us remember that popups are first class jQuery Mobile citizens, and can be treated just like anything else on the page.</p><h4>Menus</h4><p>Let&#39;s move on to something a bit more complicated: a menu. That&#39;s a popular approach to page navigation. Give the user the a menu right at their fingertips. So what does that look like with popups?</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#menu&quot; data-rel=&quot;popup&quot; data-role=&quot;button&quot;&gt;Menu&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;menu&quot; data-theme=&quot;a&quot;&gt;
    &lt;ul data-role=&quot;listview&quot; data-theme=&quot;c&quot; data-inset=&quot;true&quot;&gt;
        &lt;li data-role=&quot;divider&quot; data-theme=&quot;a&quot;&gt;My Menu&lt;/li&gt;
        &lt;li&gt;Unlinked&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;methods.html&quot;&gt;Linked&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;methods.html&quot;&gt;With count&lt;/a&gt;&lt;span class=&quot;ui-li-count&quot;&gt;42&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;
</pre><p>And the resulting output should resemble this:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popups-menu.png' alt='Popup menu' title='' border='0'></div><p>You can also use 1.2&#39;s collapsible lists in popups. Here&#39;s a quick example:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#nestedmenu&quot; data-rel=&quot;popup&quot; data-role=&quot;button&quot;&gt;Nested Menu&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;nestedmenu&quot; data-theme=&quot;none&quot;&gt;
    &lt;div data-role=&quot;collapsible-set&quot; data-theme=&quot;b&quot; data-content-theme=&quot;c&quot; data-collapsed-icon=&quot;arrow-r&quot; data-expanded-icon=&quot;arrow-d&quot; style=&quot;margin:0; width:250px;&quot;&gt;
        &lt;div data-role=&quot;collapsible&quot; data-inset=&quot;false&quot;&gt;
            &lt;h2&gt;Colors&lt;/h2&gt;
            &lt;ul data-role=&quot;listview&quot;&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Red&lt;/a&gt;&lt;/li&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Blue&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
        &lt;div data-role=&quot;collapsible&quot; data-inset=&quot;false&quot;&gt;
            &lt;h2&gt;Shapes&lt;/h2&gt;
            &lt;ul data-role=&quot;listview&quot;&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Circle&lt;/a&gt;&lt;/li&gt;
                &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Square&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre><p>And the results:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popups-nested-menu.png' alt='Popup menu' title='' border='0'></div><p>It&#39;s worth noting that <strong>data-inset=&quot;true&quot;</strong> is required on the <code>listview</code> or the corners of your list will show up. Try and you&#39;ll see.</p><h4>Forms</h4><p>Another popular UX approach is to show a login form hovering over the top of a page. That&#39;s now possible with jQuery Mobile popups. Here&#39;s a simple username/password form.</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#login&quot; data-rel=&quot;popup&quot; data-position-to=&quot;window&quot; data-role=&quot;button&quot;&gt;Login&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;login&quot; data-theme=&quot;a&quot;&gt;
    &lt;form style=&quot;padding:10px 20px;&quot;&gt;
        &lt;h3&gt;Please sign in&lt;/h3&gt;
        &lt;label for=&quot;un&quot; class=&quot;ui-hidden-accessible&quot;&gt;Username:&lt;/label&gt;
        &lt;input type=&quot;js&quot; name=&quot;user&quot; id=&quot;un&quot; placeholder=&quot;username&quot; /&gt;
        &lt;label for=&quot;pw&quot; class=&quot;ui-hidden-accessible&quot;&gt;Password:&lt;/label&gt;
        &lt;input type=&quot;password&quot; name=&quot;pass&quot; id=&quot;pw&quot; placeholder=&quot;password&quot; /&gt;
        &lt;button type=&quot;submit&quot; data-theme=&quot;b&quot;&gt;Sign in&lt;/button&gt;
    &lt;/form&gt;
&lt;/div&gt;
</pre><p>Which gives you:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-form.png' alt='Popup menu' title='' border='0'></div><p>By default, popups center themselves over the object which triggered them. There&#39;s an optional attribute which you&#39;ll see in the next three examples. It&#39;s <strong>data-position-to=&quot;window&quot;</strong> and you apply it to the element which triggers the popup. Try adding that to the <strong>Login</strong> button above to see what happens.</p><h4>Dialogs</h4><p>A common need for web applications is the ability to interact with the user. We just reviewed one approach: a login form. But, sometimes, you need to prompt the user with questions. A dialog is a perfect solution for this; and what do you know, popups have you covered! So what does that code look like? Here&#39;s a simple example:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#dialog&quot; data-rel=&quot;popup&quot; data-position-to=&quot;window&quot; data-role=&quot;button&quot; data-transition=&quot;pop&quot;&gt;Dialog&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;dialog&quot; data-overlay-theme=&quot;a&quot; data-theme=&quot;c&quot;&gt;
    &lt;div data-role=&quot;header&quot; data-theme=&quot;a&quot;&gt;
        &lt;h1&gt;Delete Page?&lt;/h1&gt;
    &lt;/div&gt;
    &lt;div data-role=&quot;content&quot; data-theme=&quot;d&quot;&gt;
        &lt;h3&gt;Are you sure you want to delete this page?&lt;/h3&gt;
        &lt;p&gt;This action cannot be undone.&lt;/p&gt;
        &lt;a href=&quot;#&quot; data-role=&quot;button&quot; data-inline=&quot;true&quot; data-rel=&quot;back&quot; data-theme=&quot;c&quot;&gt;No&lt;/a&gt;
        &lt;a href=&quot;#&quot; data-role=&quot;button&quot; data-inline=&quot;true&quot; data-rel=&quot;back&quot; data-theme=&quot;b&quot;&gt;Yes, Delete it&lt;/a&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-dialog.png' alt='Popup menu' title='' border='0'></div><p>In the popup content container, note another new attribute for your use: <strong>data-overlay-theme=&quot;a&quot;</strong>. This attribute is what applies the shaded background to the dialog box. It&#39;s affected by your theme, so be careful when working with themes created with <a
href="http://jqueryui.com/themeroller/">ThemeRoller</a>.</p><h4>Photos</h4><p>I can&#39;t count the number of times I&#39;ve seen jQuery Mobile developers ask for some better way of handling image galleries. While popups aren&#39;t the perfect solution for large numbers of images, they&#39;re great for a handful of images that need to be viewed larger. Even better, it&#8217;s incredibly easy; check it out:</p><pre class="brush: xml; title: ; notranslate">&lt;a href=&quot;#photo&quot; data-rel=&quot;popup&quot; data-position-to=&quot;window&quot; data-role=&quot;button&quot; data-transition=&quot;fade&quot;&gt;Photo&lt;/a&gt;
&lt;div data-role=&quot;popup&quot; id=&quot;photo&quot; data-overlay-theme=&quot;a&quot; data-theme=&quot;d&quot; data-corners=&quot;false&quot;&gt;
    &lt;a href=&quot;#&quot; data-rel=&quot;back&quot; data-role=&quot;button&quot; data-theme=&quot;a&quot; data-icon=&quot;delete&quot; data-iconpos=&quot;nojs&quot; class=&quot;ui-btn-right&quot;&gt;Close&lt;/a&gt;&lt;img src=&quot;http://lorempixel.com/450/300/food/&quot; /&gt;
&lt;/div&gt;
</pre><p>The above code gives you an elegant photo centered to the window, including a close window button.</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/popup-photo.png' alt='Popup menu' title='' border='0'></div><p>How did they do that? Within the context of a popup, the <code>anchor</code> tag has attributes which behave slightly different than when used in other locations on the page. Specifically, the <strong>ui-btn-right</strong> class positions the image in the corner of the image rather than the side, while the <strong>data-icon</strong> and <strong>data-iconpos</strong> attributes allow you to style the button just as you would a regular button.</p><p>You can get pretty fancy with popups including, but not limited to, displaying inline video and even interactive maps. Check the <a
href="http://jquerymobile.com/demos/1.2.0/docs/pages/popup/popup-iframes.html">jQuery Mobile documentation for popups and iframes</a>.</p><h3>Collapsible List Views</h3><p>Another great new feature is the ability to combine collapsible sets with list views. Call &#39;em &#8220;Collapsible List Views&#8221; and you&#39;ve got a brand new widget in jQuery Mobile 1.2. How do they work? I&#39;m glad you asked. Simply create any list you like, then wrap it in a collapsible set. Collapsible List Views also support multiple lists &#8211; so get crazy!</p><pre class="brush: xml; title: ; notranslate">&lt;div data-role=&quot;collapsible&quot; data-theme=&quot;b&quot; data-content-theme=&quot;c&quot;&gt;
    &lt;h2&gt;Favorite Spice Girl?&lt;/h2&gt;
    &lt;ul data-role=&quot;listview&quot;&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Posh&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Scary&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Sporty&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Baby&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Ginger&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;/div&gt;
</pre><p>The code above would result in this Collapsible List View:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/listview-collapsible.png' alt='Popup menu' title='' border='0'></div><hr
/><h2>Enhancements</h2><p>In addition to new widget types, jQuery Mobile 1.2 provides a number of useful enhancements to existing functionality. Let&#39;s take a look at some of the more valuable ones.</p><h3>jQuery Support Changes</h3><p>One of the biggest enhancements made in version 1.2 is the added support for jQuery 1.8. This brings some significant performance increases in the form of a completely rewritten Sizzle.js (the selector engine for jQuery), along with numerous other improvements.</p><p>The tradeoff is that the jQuery Mobile team decided that it was time to sunset support for jQuery 1.6. This may be unfortunate  for some folks out there who are still using older versions of jQuery, but it&#8217;s a fair trade.</p><h3>List View Autodividers</h3><p>If you&#39;ve ever had to manage a list of constantly changing people, places, or things in jQuery Mobile then, you&#39;ve probably had to write some tricky code to display dynamic listview headers. Bummer that you spent all that time, because the jQuery Mobile team made it as easy as dropping in a single attribute.</p><pre class="brush: jscript; title: ; notranslate">data-autodividers=&quot;true&quot;
</pre><p>That turns this list:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/listview-dividers-before.png' alt='Popup menu' title='' border='0'></div><p>Into:</p><div
class='tutorial_image'><img
src='http://d2o0t5hpnwv4c1.cloudfront.net/2150_NewInjQueryMobile/images/listview-dividers-after.png' alt='Popup menu' title='' border='0'></div><p>Note that this does not manage sorting, grouping, or filtering. For that sort of functionality, consider trying my <a
href="http://andymatthews.net/code/jqm-tinysort/">jQuery Mobile Tinysort plugin</a>.</p><h3>Read-Only Lists</h3><p>jQuery Mobile offers &quot;read-only&quot; list views, but it was difficult to tell that they weren&#39;t clickable. Version 1.2 removes the list gradient, making the row a flat color. This should provide a better visual cue to your users.</p><h3>Better Width adjustments on Form Elements</h3><p>Version 1.2 fixes a semi-annoying issue with form elements, whereby they wouldn&#39;t take up the full width of their parent element in some cases.</p><h3>Additional Devices Added</h3><p>You might have noticed that new devices are being added almost on a daily basis. The jQuery Mobile team does their best to test against as many of these devices as possible. Newly added to the A grade platform list are the following devices/operating systems/browsers: iOS 6, Android 4.1 (Jellybean), Tizen, Firefox for Android, and Kindle Fire HD.</p><hr
/><h2>Full List of Changes</h2><p>You can find a complete list of the changes made for version 1.2 on the <a
href="http://jquerymobile.com/blog/2012/10/02/announcing-jquery-mobile-1-2-0-final/#changelog">jQuery Mobile blog</a>.</p><p>I hope that some of these improvements will help to improve your applications. Remember that the jQuery Mobile team is on your side! If you see something that you think would be valuable, ask for it: create an issue in <a
href="https://github.com/jquery/jquery-mobile">their Github repository</a>, and suggest it. Better yet, fork their repo and add some code yourself!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/0/da"><img src="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/1/da"><img src="http://feedads.g.doubleclick.net/~a/H_gBMBIfaYo_YEdZJQs2u73kjD4/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=05Uf-v1kENc:lJNanzsjGks:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=05Uf-v1kENc:lJNanzsjGks:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=05Uf-v1kENc:lJNanzsjGks:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=05Uf-v1kENc:lJNanzsjGks:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/05Uf-v1kENc" height="1" width="1"/>";s:14:"date_timestamp";i:1352214241;}i:6;a:13:{s:5:"title";s:29:"Best of Tuts+ in October 2012";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/n3HCLGxAt4Q/";s:8:"comments";s:89:"http://net.tutsplus.com/articles/roundups-articles/best-of-tuts-in-october-2012/#comments";s:7:"pubdate";s:31:"Mon, 05 Nov 2012 14:49:24 +0000";s:2:"dc";a:1:{s:7:"creator";s:13:"Joel Bankhead";}s:8:"category";s:25:"Roundupsbestoftutsoctober";s:4:"guid";s:32:"http://net.tutsplus.com/?p=27932";s:11:"description";s:36990:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27932&c=1327105711' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27932&c=1327105711' border='0' alt='' /></a><p>Each month, we bring together a selection of the best tutorials and articles from across the whole <a
href="http://tutsplus.com/">Tuts+ network</a>. Whether you&#8217;d like to read the top posts from your favourite site, or would like to start learning something completely new, this is the best place to start!</p><p><span
id="more-27932"></span></p><hr
/><h2>Psdtuts+ — Photoshop Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="https://d2f8dzk2mhcqts.cloudfront.net/0754_Game/preview.jpg" alt="Draw a Retro Gameboy From Scratch in Photoshop" width="200" height="200" /></div><h4><a
href='http://psd.tutsplus.com/tutorials/icon-design/retro-gameboy-photoshop/'>Draw a Retro Gameboy From Scratch in Photoshop</a></h4><p>Attempting to replicate real life objects in Photoshop is great practice. In this tutorial we will explain how to create a realistic, retro Gameboy device using Photoshop&#8217;s powerful feature set. Let&#8217;s get started!</p><p><a
href='http://psd.tutsplus.com/tutorials/icon-design/retro-gameboy-photoshop/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2f8dzk2mhcqts.cloudfront.net/0763_Denim/preview.jpg" alt="Create a Stitched Denim Text Effect in Photoshop" width="200" height="200" /></div><h4><a
href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/stitched-denim-text-effect/'>Create a Stitched Denim Text Effect in Photoshop</a></h4><p>In this tutorial, we will explain how to combine Photoshop filters, brushes, and vector shapes to create a stitched denim text effect using Photoshop CS6. Let&#8217;s get started!</p><p><a
href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/stitched-denim-text-effect/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2f8dzk2mhcqts.cloudfront.net/0769_Two_Face/preview.jpg" alt="Create a &#8220;Two-Faced&#8221; Digital Painting in Photoshop" width="200" height="200" /></div><h4><a
href='http://psd.tutsplus.com/tutorials/painting/two-faced-digital-painting/'>Create a &#8220;Two-Faced&#8221; Digital Painting in Photoshop</a></h4><p>Creating a nice character painting in Photoshop can be a difficult but rewarding task. In this tutorial, we will explain how to create a classic Batman villain in Photoshop. Let&#8217;s get started!</p><p><a
href='http://psd.tutsplus.com/tutorials/painting/two-faced-digital-painting/'>Visit Article</a></p></li></ul><hr
/><h2>Nettuts+ — Web Development Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2144_Bower/preview.jpeg" alt="Meet Bower: A Package Manager For The Web" width="200" height="200" /></div><h4><a
href='http://net.tutsplus.com/tutorials/tools-and-tips/meet-bower-a-package-manager-for-the-web/'>Meet Bower: A Package Manager For The Web</a></h4><p>As the web platform has matured, the tools for managing our projects, too, have matured. In this tutorial, I&#8217;ll introduce you to one of these tools that makes managing the dependencies of your project considerably easier: <a
href="http://twitter.github.com/bower/" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','twitter.github.com']);">Bower</a>.</p><p><a
href='http://net.tutsplus.com/tutorials/tools-and-tips/meet-bower-a-package-manager-for-the-web/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2142_MakeJSTestingFunWithTestem/make-javascript-testing-fun-with-testem.jpg" alt="Make JavaScript Testing Fun With Testem" width="200" height="200" /></div><h4><a
href='http://net.tutsplus.com/tutorials/javascript-ajax/make-javascript-testing-fun-with-testem/'>Make JavaScript Testing Fun With Testem</a></h4><p>JavaScript testing is a sensitive subject. Some developers are huge advocates of it (including myself), while others don&#8217;t see the need or benefit. One huge barrier is the simple fact that it can sometimes take a considerable amount of setup to get up and running. The longer it takes, the more likely it is that the developer simply won&#8217;t bother. That&#8217;s why <a
href="https://github.com/airportyh/testem" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','github.com']);">Testem</a> is so fantastic; it makes testing as effortless as possible, and, more importantly, fun!<br
/> <span
id="more-27738"></span></p><p><a
href='http://net.tutsplus.com/tutorials/javascript-ajax/make-javascript-testing-fun-with-testem/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2132_TDDPHP/introduction.jpg" alt="" width="200" height="200" /></div><h4><a
href='http://net.tutsplus.com/sessions/test-driven-php/'>Test Driven PHP Session</a></h4><p>Let’s be honest: the PHP community hasn’t been as quick to the test-driven development scene as other communities, such as those around the Ruby and Python languages. We hope to help change that on Nettuts+! In this session, you’ll learn both why and how to test-drive your applications using the fantastic PHPUnit. Ready?<br
/> <span
id="more-27738"></span></p><p><a
href='http://net.tutsplus.com/sessions/test-driven-php/'>Visit Article</a></p></li></ul><hr
/><h2>Vectortuts+ — Illustrator Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://dsmy2muqb7t4m.cloudfront.net/articles/2012/article_bad_logo/preview.jpg" alt="Stop Making Bad Logos" width="200" height="200" /></div><h4><a
href='http://vector.tutsplus.com/articles/theory/stop-making-bad-logos/'>Stop Making Bad Logos</a></h4><p>There&#8217;s article after article on websites that talk bout how to make a great logo. But If you&#8217;re a logo machine, and you&#8217;ve been doing it for a long time, chances are that you&#8217;ve developed some pretty awful habits. How do I know this? Because I suffered from some of the same habits I&#8217;m about to talk about. A true master of logo creation will refine their work on every project, forcing themselves to get better with each design. It all boils down to a few key things to avoid when you&#8217;re creating a logo. While you can take a stab at selling generic logos on places like GraphicRiver, you&#8217;ll do your best work when you deeply understand your clients and their company.</p><p><a
href='http://vector.tutsplus.com/articles/theory/stop-making-bad-logos/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://dsmy2muqb7t4m.cloudfront.net/tuts/000-2012/564_geometric_portrait/Final_Image_PVW_Self_Portrait.jpg" alt="How to Create a Self Portrait in a Geometric Style" width="200" height="200" /></div><h4><a
href='http://vector.tutsplus.com/tutorials/illustration/how-to-create-a-self-portrait-in-a-geometric-style/'>How to Create a Self Portrait in a Geometric Style</a></h4><p>In this tutorial we are going to talk about how to create an illustrated self portrait in a geometric based style. We are going to work from a photograph of ourselves as the base of the illustration, then drawing the sketch and to the final piece, so lets get started.</p><p><a
href='http://vector.tutsplus.com/tutorials/illustration/how-to-create-a-self-portrait-in-a-geometric-style/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://dsmy2muqb7t4m.cloudfront.net/tuts/000-2012/555_paisley/images/preview.jpg" alt="Creating Paisley Graphic Styles with Scatter Brushes and Recolor Artwork" width="200" height="200" /></div><h4><a
href='http://vector.tutsplus.com/tutorials/tools-tips/creating-paisley-graphic-styles-with-scatter-brushes-and-recolor-artwork/'>Creating Paisley Graphic Styles with Scatter Brushes and Recolor Artwork</a></h4><p>In today&#8217;s tutorial I&#8217;m going to show you how to create a series of Paisley inspired Graphic Styles using Scatter Brushes and the Appearance panel. Once done, I&#8217;ll show you how to create additional styles simply by using Recolor Artwork. This is a great tutorial for beginners as there is no Pen Tool (P) involved. So let&#8217;s begin!</p><p><a
href='http://vector.tutsplus.com/tutorials/tools-tips/creating-paisley-graphic-styles-with-scatter-brushes-and-recolor-artwork/'>Visit Article</a></p></li></ul><hr
/><h2>Webdesigntuts+ — Web Design Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d3pr5r64n04s3o.cloudfront.net/tuts/397_performance/tutimages/preview.png" alt="Best Practices for Increasing Website Performance" width="200" height="200" /></div><h4><a
href='http://webdesign.tutsplus.com/tutorials/workflow-tutorials/best-practices-for-increasing-web-site-performance/'>Best Practices for Increasing Website Performance</a></h4><p>It&#8217;s a no-brainer: well performing websites enjoy higher visitor engagement, retention and conversion. Given how fickle users can be, plus the fact that mobile devices are very significant these days, never before has the speed of websites been so important! In this article I&#8217;m going to highlight ways in which you can improve the performance of your own sites.</p><p><a
href='http://webdesign.tutsplus.com/tutorials/workflow-tutorials/best-practices-for-increasing-web-site-performance/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3pr5r64n04s3o.cloudfront.net/articles/105_buildwindows/preview.png" alt="How They Did It: Build Windows" width="200" height="200" /></div><h4><a
href='http://webdesign.tutsplus.com/articles/general/how-they-did-it-build-windows/'>How They Did It: Build Windows</a></h4><p>Today, we&#8217;ll dive into <a
href="http://buildwindows.com" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','buildwindows.com']);">the Build Windows site</a> and look at the practical code philosophies, tools, and strategies used by this highly trafficked, highly praised conference landing page. We&#8217;ll get into the nitty gritty, but we will also be covering some things from a mile-high perspective.</p><p><a
href='http://webdesign.tutsplus.com/articles/general/how-they-did-it-build-windows/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3pr5r64n04s3o.cloudfront.net/tuts/391_checkboxes/preview.png" alt="Quick Tip: Easy CSS3 Checkboxes and Radio Buttons" width="200" height="200" /></div><h4><a
href='http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/quick-tip-easy-css3-checkboxes-and-radio-buttons/'>Quick Tip: Easy CSS3 Checkboxes and Radio Buttons</a></h4><p>Ever wondered how to style checkboxes and radio buttons, but without JavaScript? Thanks to CSS3 you can!</p><p><a
href='http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/quick-tip-easy-css3-checkboxes-and-radio-buttons/'>Visit Article</a></p></li></ul><hr
/><h2>Phototuts+ — Photography Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d2f29brjr0xbt3.cloudfront.net/984_jackolantern/preview.jpg" alt="How to Make Fantastically Fun Jack &#8216;O Lantern Photos" width="200" height="200" /></div><h4><a
href='http://photo.tutsplus.com/articles/shooting-articles/how-to-make-fantastically-fun-jack-o-lantern-photos/'>How to Make Fantastically Fun Jack &#8216;O Lantern Photos</a></h4><p>&#8220;Trick or treat!&#8221; Halloween is knocking on the door. It is a very popular holiday in many countries. It brings the spirit of mystic, fear, magic and fairy. Halloween can be a great inspiration for shooting some beautiful lights -&#8221; all those jack-o-lanterns and candles.<span
id="more-10419"></span></p><p><a
href='http://photo.tutsplus.com/articles/shooting-articles/how-to-make-fantastically-fun-jack-o-lantern-photos/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/photo.tutsplus.com/Diana%20Eftaiha/2012/10/08/Adding-a-sense-of-depth-to-your-photos.jpg" alt="How to Create a Sense of Depth to Your Photos" width="200" height="200" /></div><h4><a
href='http://photo.tutsplus.com/articles/composition-articles/how-to-create-a-sense-of-depth-to-your-photos/'>How to Create a Sense of Depth to Your Photos</a></h4><p>Today we will take a look at how to add some sense of depth to your photographs and thus make them become alive and more interesting to the viewer. By making use of some simple but very effective factors that can be applied at the time of exposure, you can make a your picture pop. Today, we&#8217;ll talk about perspective, depth of field, and framing.</p><p><a
href='http://photo.tutsplus.com/articles/composition-articles/how-to-create-a-sense-of-depth-to-your-photos/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/photo.tutsplus.com/Rob%20Taylor/2012/10/03/preview.jpg" alt="Dealing With Foliage: Green and Yellow Saturation" width="200" height="200" /></div><h4><a
href='http://photo.tutsplus.com/articles/dealing-with-foliage-green-and-yellow-saturation/'>Dealing With Foliage: Green and Yellow Saturation</a></h4><p>I&#8217;ve noticed around the internet that a great many people struggle with foliage. A large number of people don&#8217;t even seem to notice that there&#8217;s an issue, which is unfortunately falsely backed up by the legions of commenters trying to be nice rather than truthful. The problem persists for all levels of photographers, from year one amateurs to multi-year pros.<span
id="more-10127"></span></p><p><a
href='http://photo.tutsplus.com/articles/dealing-with-foliage-green-and-yellow-saturation/'>Visit Article</a></p></li></ul><hr
/><h2>Cgtuts+ — Computer Graphics Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d2d04grx5ahzvh.cloudfront.net/455_iPhone_4S_PT4/iPhone_Thumb.jpg" alt="Creating The iPhone 4S In 3D Studio Max, Part 4 Texturing &#038; Rendering with V-Ray" width="200" height="200" /></div><h4><a
href='http://cg.tutsplus.com/tutorials/autodesk-3d-studio-max/creating-the-iphone-4s-in-3d-studio-max-part-4-texturing-rendering-with-v-ray/'>Creating The iPhone 4S In 3D Studio Max, Part 4 Texturing &#038; Rendering with V-Ray</a></h4><p>In the fourth part of the iPhone series we&#8217;ll begin creating textures and the many shaders needed for our model. While most will be procedural materials, a few of the elements do require image based textures, so we&#8217;ll first tackle the uvmapping on these elements. We&#8217;ll then move on and construct a studio lighting rig using V-Ray lights and introduce image based lighting to the scene. Along the way we&#8217;ll rely heavily on the power of V-Ray&#8217;s RT engine to fine tune our materials, lighting and render settings to balance the scene and achieve the look we&#8217;re after for our final render.</p><p><a
href='http://cg.tutsplus.com/tutorials/autodesk-3d-studio-max/creating-the-iphone-4s-in-3d-studio-max-part-4-texturing-rendering-with-v-ray/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2d04grx5ahzvh.cloudfront.net/451_Maya_IceCream_PT1/Thumb_PT1.png" alt="Creating an Ice Cream Bar Animation with Maya, RealFlow And AE &#8211; Part 1" width="200" height="200" /></div><h4><a
href='http://cg.tutsplus.com/tutorials/autodesk-maya/creating-an-ice-cream-bar-animation-with-maya-realflow-and-ae-part-1/'>Creating an Ice Cream Bar Animation with Maya, RealFlow And AE &#8211; Part 1</a></h4><p>Hey folks, in this three part tutorial spanning both Cgtuts+ and<a
href="http://ae.tutsplus.com/" > Aetuts+</a>, we are going to create liquid chocolate pouring over a branded ice cream bar. To achieve this we will use Maya for mashing and rendering. RealFlow for the chocolate simulation. And finally in After Effects we&#8217;ll create the chocolate chunks and glow streaks swoosh, as well as the final compositing.<span
id="more-17866"></span></p><p><a
href='http://cg.tutsplus.com/tutorials/autodesk-maya/creating-an-ice-cream-bar-animation-with-maya-realflow-and-ae-part-1/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tutsplus.s3.amazonaws.com/tutspremium/3d-graphics/92_Faux_Energy_Drink/Thumb.jpg" alt="Create a High Impact Faux Energy Drink Ad with 3D Studio Max, Cinema 4D &#038; AE &#8211; Tuts+ Premium" width="200" height="200" /></div><h4><a
href='http://cg.tutsplus.com/tutorials/maxon-cinema-4d/create-a-high-impact-faux-energy-drink-ad-with-3d-studio-max-cinema-4d-ae-tuts-premium/'>Create a High Impact Faux Energy Drink Ad with 3D Studio Max, Cinema 4D &#038; AE &#8211; Tuts+ Premium</a></h4><p>In this tutorial we are going to create from start to finish an interesting short four shot ad cut for a fake energy drink &rsquo;Envato Energy&#8221;. This will give you some guidance on how to create something similar for a real life project.</p><p><a
href='http://cg.tutsplus.com/tutorials/maxon-cinema-4d/create-a-high-impact-faux-energy-drink-ad-with-3d-studio-max-cinema-4d-ae-tuts-premium/'>Visit Article</a></p></li></ul><hr
/><h2>Aetuts+ — After Effects Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d3gphd0pfuxn95.cloudfront.net/816_groundbreak/thumbnail.jpg" alt="Create A Ground Breaking Pavement Crack Simulation" width="200" height="200" /></div><h4><a
href='http://ae.tutsplus.com/tutorials/vfx/create-a-ground-breaking-pavement-crack-simulation/'>Create A Ground Breaking Pavement Crack Simulation</a></h4><p>In this tutorial we will learn how to properly create a good workflow between After Effects and Cinema 4D. In the process we are going to take a look at how to create your own custom ground cracking overlays for compositing.<br
/> <span
id="more-22265"></span></p><p><a
href='http://ae.tutsplus.com/tutorials/vfx/create-a-ground-breaking-pavement-crack-simulation/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3gphd0pfuxn95.cloudfront.net/814_coverflow/cover_flow_thumbnail.jpg" alt="How To Use The Amazing Free New Preset &#8220;Cover Flow&#8221;" width="200" height="200" /></div><h4><a
href='http://ae.tutsplus.com/tutorials/workflow/how-to-use-the-amazing-free-new-preset-cover-flow/'>How To Use The Amazing Free New Preset &#8220;Cover Flow&#8221;</a></h4><p>Cover Flow is a preset for AE to create the <a
href="http://en.wikipedia.org/wiki/Cover_Flow" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','en.wikipedia.org']);">classic flowing cover effect</a> best known from iTunes. On top of that it has several options to change the result like adding randomness to the position of the layers, adding blur to fake a depth of field and so on. Today we&#8217;ll walk you through how to install and use this tool.</p><p><a
href='http://ae.tutsplus.com/tutorials/workflow/how-to-use-the-amazing-free-new-preset-cover-flow/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3gphd0pfuxn95.cloudfront.net/815_batman/thumbnailbatman.jpg" alt="Illustrator to After Effects Relation-tips &#8211; Batman Vector Animation" width="200" height="200" /></div><h4><a
href='http://ae.tutsplus.com/tutorials/motion-graphics/illustrator-to-after-effects-relation-tips-batman-vector-animation/'>Illustrator to After Effects Relation-tips &#8211; Batman Vector Animation</a></h4><p>This the first tutorial of a four part series where we are going to show some of the most common and widely used effects for After Effects.</p><p><a
href='http://ae.tutsplus.com/tutorials/motion-graphics/illustrator-to-after-effects-relation-tips-batman-vector-animation/'>Visit Article</a></p></li></ul><hr
/><h2>Audiotuts+ — Audio &amp; Production Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d3vvl31cy8gagb.cloudfront.net/779_livesound/preview.jpg" alt="How to Enhance a Live, Out-of-the-Mixer Concert Recording" width="200" height="200" /></div><h4><a
href='http://audio.tutsplus.com/tutorials/mixing-mastering/how-to-enhance-a-live-out-of-the-mixer-concert-recording/'>How to Enhance a Live, Out-of-the-Mixer Concert Recording</a></h4><p>I was playing at a concert recently where I had the fortune on getting my hands on a 2-track recording out of the FOH mixer. I playing at a festival and all the stages recorded the acts, giving them a CD at the end of their set. Usually, a recording such as this is done straight out of the L/R OUT of the mixer. All the channels of the mixer are fed to the stereo out that&#8217;s fed into a stereo recorder. The recording is then burned onto a CD for the bands to listen to.<br
/> <span
id="more-15067"></span></p><p><a
href='http://audio.tutsplus.com/tutorials/mixing-mastering/how-to-enhance-a-live-out-of-the-mixer-concert-recording/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3vvl31cy8gagb.cloudfront.net/784_synth/preview.jpg" alt="Essential Subtractive Synthesis: Envelopes" width="200" height="200" /></div><h4><a
href='http://audio.tutsplus.com/tutorials/sound-design/essential-subtractive-synthesis-envelopes/'>Essential Subtractive Synthesis: Envelopes</a></h4><p>This is a series of basic synthesis workshops. We assume you&#8217;re not entirely new to synthesizers, but you&#8217;re not an expert either. Today we look at envelopes.</p><p><a
href='http://audio.tutsplus.com/tutorials/sound-design/essential-subtractive-synthesis-envelopes/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3vvl31cy8gagb.cloudfront.net/782_listening/preview.jpg" alt="Essential Listening &#8211; Getting Critical" width="200" height="200" /></div><h4><a
href='http://audio.tutsplus.com/articles/general/essential-listening-getting-critical/'>Essential Listening &#8211; Getting Critical</a></h4><p>Welcome back for another round of Essential Listening. Last time we took a look at some of the big albums of all time and how the mixes were so different, but at the same time all great. And while we will certainly revisit looking at some classic songs and albums from an engineering standpoint down the road, today is all about improving your critical listening skills.</p><p><a
href='http://audio.tutsplus.com/articles/general/essential-listening-getting-critical/'>Visit Article</a></p></li></ul><hr
/><h2>Wptuts+ — WordPress Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://tutsplus.s3.amazonaws.com/writefortuts/writefortuts.jpg" alt="WANTED: WordPress Professionals With a Passion for Education. Enquire Within." width="200" height="200" /></div><h4><a
href='http://wp.tutsplus.com/articles/news/wanted-wordpress-professionals-with-a-passion-for-education-enquire-within/'>WANTED: WordPress Professionals With a Passion for Education. Enquire Within.</a></h4><p><strong>Are you an experienced WordPress professional with a desire to educate others on standards and best practices?</strong> If so, we&#8217;d like to speak with you about writing for Wptuts+ 1-4 times per month. We&#8217;d like you to submit at least one article a month, and you&#8217;re free to choose your topics, as long as they appeal to our audience. <strong>This is a paid job.</strong> If you&#8217;re interesting in helping educate others in The WordPress Way, read on.<span
id="more-27549"></span></p><p><a
href='http://wp.tutsplus.com/articles/news/wanted-wordpress-professionals-with-a-passion-for-education-enquire-within/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/wp.tutsplus.com/Japh/2012/10/12/preview.png" alt="Building a Simple Announcements Plugin for WordPress" width="200" height="200" /></div><h4><a
href='http://wp.tutsplus.com/tutorials/plugins/building-a-simple-announcements-plugin-for-wordpress/'>Building a Simple Announcements Plugin for WordPress</a></h4><p>Let&#8217;s say that you&#8217;re a launching new product, giving away freebies or organizing an event. How do you deliver the message to your readers? Popular choice is to display a modal dialog in a lightbox, thus forcing the user to take notice. But there&#8217;s another, less obtrusive, yet still effective way, to get a user&#8217;s attention. In this tutorial we&#8217;ll be creating a plugin that displays custom site-wide announcements across the top of the page, with the ability to schedule messages to appear between two given dates.<span
id="more-27661"></span></p><p><a
href='http://wp.tutsplus.com/tutorials/plugins/building-a-simple-announcements-plugin-for-wordpress/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/wp.tutsplus.com/Japh/2012/10/17/The-Beginners-Guide-To-WordPress-Actions-and-Filters.jpg" alt="The Beginner&#8217;s Guide to WordPress Actions and Filters" width="200" height="200" /></div><h4><a
href='http://wp.tutsplus.com/tutorials/the-beginners-guide-to-wordpress-actions-and-filters/'>The Beginner&#8217;s Guide to WordPress Actions and Filters</a></h4><p>When it comes to professional WordPress development, it&#8217;s imperative that developers understand both actions and filters &#8211; that is, it&#8217;s important to understand WordPress hooks.</p><p><a
href='http://wp.tutsplus.com/tutorials/the-beginners-guide-to-wordpress-actions-and-filters/'>Visit Article</a></p></li></ul><hr
/><h2>Mobiletuts+ — Mobile Development Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="https://d339vfjsz5zott.cloudfront.net/iPhone5_Display/iPhone5-Display_iOS6.png" alt="Working with the iPhone 5 Display" width="200" height="200" /></div><h4><a
href='http://mobile.tutsplus.com/tutorials/iphone/working-with-the-iphone-5-display/'>Working with the iPhone 5 Display</a></h4><p>This tutorial will review the steps necessary to ensure that your iOS apps will continue to look great when displayed on the new iPhone 5 screen.<br
/> <span
id="more-12938"></span></p><p><a
href='http://mobile.tutsplus.com/tutorials/iphone/working-with-the-iphone-5-display/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="https://d339vfjsz5zott.cloudfront.net/miscfiles/previews/iOS-Drawing_Preview.png" alt="Smooth Freehand Drawing on iOS" width="200" height="200" /></div><h4><a
href='http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_freehand-drawing/'>Smooth Freehand Drawing on iOS</a></h4><p>This tutorial will teach you how to implement an advanced drawing algorithm for smooth, freehand drawing on iOS devices. Read on!<br
/> <span
id="more-13164"></span></p><p><a
href='http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_freehand-drawing/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="https://d339vfjsz5zott.cloudfront.net/Android-ASCII-Editor/Android-ASCII_Preview.png" alt="Build an ASCII Art Editor: Interface Setup" width="200" height="200" /></div><h4><a
href='http://mobile.tutsplus.com/tutorials/android/build-an-ascii-art-editor-interface-setup/'>Build an ASCII Art Editor: Interface Setup</a></h4><p>The Android platform offers a wide range of storage options for use within your apps. In this tutorial series, we are going to explore some of the data storage facilities provided by the Android SDK by building a simple project: an ASCII art editor.<br
/> <span
id="more-12791"></span></p><p><a
href='http://mobile.tutsplus.com/tutorials/android/build-an-ascii-art-editor-interface-setup/'>Visit Article</a></p></li></ul><hr
/><h2>Gamedevtuts+ — Game Development</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Tomislav%20Podhraski/2012/10/06/Preview2.png" alt="Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders" width="200" height="200" /></div><h4><a
href='http://gamedev.tutsplus.com/tutorials/implementation/create-a-glowing-flowing-lava-river-using-bezier-curves-and-shaders/'>Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders</a></h4><p>Most of the time, using conventional graphic techniques is the right way to go. Sometimes, though, experimentation and creativity at the fundamental levels of an effect can be beneficial to the style of the game, making it stand out more. In this tutorial I&#8217;m going to show you how to create an animated 2D lava river using Bézier curves, custom textured geometry and vertex shaders.<span
id="more-919"></span></p><p><a
href='http://gamedev.tutsplus.com/tutorials/implementation/create-a-glowing-flowing-lava-river-using-bezier-curves-and-shaders/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://gamedevtuts.s3.amazonaws.com/039_howToLearnUnity/How_To_Learn_Unity.jpg" alt="How to Learn Unity" width="200" height="200" /></div><h4><a
href='http://gamedev.tutsplus.com/articles/how-to-learn/how-to-learn-unity/'>How to Learn Unity</a></h4><p>Unity is a feature rich, fully integrated development engine for the creation of interactive 3D content. You want to make 3D games? Unity&#8217;s got you covered. In this article we&#8217;ll share books, tutorials and suggestions for getting to grips with Unity.<span
id="more-1333"></span></p><p><a
href='http://gamedev.tutsplus.com/articles/how-to-learn/how-to-learn-unity/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Paul%20Suddaby/2012/10/23/Heavy_Rain_Logo.jpg" alt="How Heavy Rain&#8217;s Narrative Is Strengthened by Its Gameplay" width="200" height="200" /></div><h4><a
href='http://gamedev.tutsplus.com/articles/game-design-articles/how-heavy-rains-narrative-is-strengthened-by-its-gameplay/'>How Heavy Rain&#8217;s Narrative Is Strengthened by Its Gameplay</a></h4><p>Heavy Rain received immense critical praise for being an experience that elevated video game storytelling to a new level. In this article, we&#8217;ll look at why that is and what we can learn from it.</p><p><a
href='http://gamedev.tutsplus.com/articles/game-design-articles/how-heavy-rains-narrative-is-strengthened-by-its-gameplay/'>Visit Article</a></p></li></ul><hr
/><h2>Mactuts+ — Mac &#038; OS X</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/mac.tutsplus.com/Josh%20Johnson/2012/10/02/geektool-f.png" alt="5 Ways to Make Your Mac&#8217;s Desktop Better with GeekTool" width="200" height="200" /></div><h4><a
href='http://mac.tutsplus.com/tutorials/customization/5-ways-to-make-your-macs-desktop-better-with-geektool/'>Ways to Make Your Mac&#8217;s Desktop Better with GeekTool</a></h4><p>GeekTool is an amazing free app that is a bit like Dashboard for the super nerdy. It allows you to place functional widgets, called &#8220;Geeklets,&#8221; right on top of your desktop, so you can always see them. Implementation can be a little tricky though so this tutorial will walk you through five different ways to use Geeklets to enhance your desktop experience.</p><p><a
href='http://mac.tutsplus.com/tutorials/customization/5-ways-to-make-your-macs-desktop-better-with-geektool/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/mac.tutsplus.com/John%20Winter/2012/09/13/tlphn-icon.png" alt="How to Set Up and Use VoIP on Your Mac" width="200" height="200" /></div><h4><a
href='http://mac.tutsplus.com/tutorials/productivity/how-to-set-up-and-use-voip-on-your-mac/'>How to Set Up and Use VoIP on Your Mac</a></h4><p>With the advent of faster broadband, the viability of using your data connection for voice communications has become increasingly reliable. VoIP has lower startup and ongoing costs than traditional, fixed-line telephones and has a wealth of flexible features that are often additional cost options from your dinosaur-era fixed-line phone network.  If you are a freelancer, a business owner, or even just home user who requires a separate telephone from your home number, then VoIP is for you.</p><p><a
href='http://mac.tutsplus.com/tutorials/productivity/how-to-set-up-and-use-voip-on-your-mac/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="https://tuts-authors.s3.amazonaws.com/mac.tutsplus.com/John%20Pavlovits/2012/09/02/Terminal%20Tutorial%20Icon.png" alt="Quick Tip: Trick Out Your Mac with Terminal" width="200" height="200" /></div><h4><a
href='http://mac.tutsplus.com/tutorials/terminal/quick-tip-trick-out-your-mac-with-terminal/'>Quick Tip: Trick Out Your Mac with Terminal</a></h4><p>The Mac OS X operating system is already really sleek, but we&#8217;re going to look at how to use terminal to activate some cool hidden settings that will make your Mac even better. The terminal tricks I&#8217;ll be showing you range from adding spaces to your dock to freeing your Dashboard widgets from the Dashboard. So let&#8217;s get started!<br
/> <span
id="more-31318"></span></p><p><a
href='http://mac.tutsplus.com/tutorials/terminal/quick-tip-trick-out-your-mac-with-terminal/'>Visit Article</a></p></li></ul><hr
/><h2>FreelanceSwitch — Freelance Jobs &#038; Information</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://freelanceswitch.com/wp-content/uploads/2012/10/Payday-dollars-hand-businessman.jpg" alt="" width="200" height="200" /></div><h4><a
href='http://freelanceswitch.com/the-business-of-freelancing/raise-your-freelance-rates/'>How to Raise Your Freelance Pay Rates in the Next 60 Days</a></h4><p>Freelancers interested in earning big should always be looking for opportunities to raise rates. Luckily, if you’re reading this in the fall, you’re at one of the easiest times of year to get a raise.<br
/> I’ll explain why in a minute. <br
/> But first, let’s talk a little economic reality about why you need to get aggressive about asking for a raise.</p><p><a
href='http://freelanceswitch.com/the-business-of-freelancing/raise-your-freelance-rates/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://freelanceswitch.s3.amazonaws.com/previewimages/2012/How-to-Set-Up-Your-LinkedIn-Profile-Freelancer-Guide.png" alt="" width="200" height="200" /></div><h4><a
href='http://freelanceswitch.com/freelance-marketing/set-up-your-linkedin-profile/'>How to Set Up Your LinkedIn Profile: A Freelancer’s Guide</a></h4><p>LinkedIn makes sense for professionals, but what about for freelancers?<br
/> In my experience, LinkedIn is an important tool in my marketing toolbox. Being on LinkedIn allows me to showcase my skills and experience. Additionally, LinkedIn is a networking platform, which makes it perfect for finding prospects, hooking up with new clients or reconnecting with past clients.</p><p><a
href='http://freelanceswitch.com/freelance-marketing/set-up-your-linkedin-profile/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://freelanceswitch.s3.amazonaws.com/previewimages/2012/How-Write-Effective-Freelancer-About-Page.png" alt="" width="200" height="200" /></div><h4><a
href='http://freelanceswitch.com/freelancing-essentials/freelancer-about-page/'>How to Write an Effective Freelancer About Page</a></h4><p>The most visited page on most websites is the about page. That holds particularly true for freelancers — on my site, almost half of my visitors wind up there. That’s because a client looking to hire some help wants to know exactly who he’ll be working with. <br
/> When he’s found you online, he’s not going to have a sense of who you are and why you’re worth your rates until he’s found out more. Your about page is the easiest way to do so.<br
/> <span
id="more-31318"></span></p><p><a
href='http://freelanceswitch.com/freelancing-essentials/freelancer-about-page/'>Visit Article</a></p></li></ul>
<p><a href="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/0/da"><img src="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/1/da"><img src="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=n3HCLGxAt4Q:ZXavmXnxJpA:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=n3HCLGxAt4Q:ZXavmXnxJpA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=n3HCLGxAt4Q:ZXavmXnxJpA:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/n3HCLGxAt4Q" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:85:"http://net.tutsplus.com/articles/roundups-articles/best-of-tuts-in-october-2012/feed/";}s:5:"slash";a:1:{s:8:"comments";s:1:"0";}s:10:"feedburner";a:1:{s:8:"origlink";s:80:"http://net.tutsplus.com/articles/roundups-articles/best-of-tuts-in-october-2012/";}s:7:"summary";s:36990:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27932&c=1327105711' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27932&c=1327105711' border='0' alt='' /></a><p>Each month, we bring together a selection of the best tutorials and articles from across the whole <a
href="http://tutsplus.com/">Tuts+ network</a>. Whether you&#8217;d like to read the top posts from your favourite site, or would like to start learning something completely new, this is the best place to start!</p><p><span
id="more-27932"></span></p><hr
/><h2>Psdtuts+ — Photoshop Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="https://d2f8dzk2mhcqts.cloudfront.net/0754_Game/preview.jpg" alt="Draw a Retro Gameboy From Scratch in Photoshop" width="200" height="200" /></div><h4><a
href='http://psd.tutsplus.com/tutorials/icon-design/retro-gameboy-photoshop/'>Draw a Retro Gameboy From Scratch in Photoshop</a></h4><p>Attempting to replicate real life objects in Photoshop is great practice. In this tutorial we will explain how to create a realistic, retro Gameboy device using Photoshop&#8217;s powerful feature set. Let&#8217;s get started!</p><p><a
href='http://psd.tutsplus.com/tutorials/icon-design/retro-gameboy-photoshop/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2f8dzk2mhcqts.cloudfront.net/0763_Denim/preview.jpg" alt="Create a Stitched Denim Text Effect in Photoshop" width="200" height="200" /></div><h4><a
href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/stitched-denim-text-effect/'>Create a Stitched Denim Text Effect in Photoshop</a></h4><p>In this tutorial, we will explain how to combine Photoshop filters, brushes, and vector shapes to create a stitched denim text effect using Photoshop CS6. Let&#8217;s get started!</p><p><a
href='http://psd.tutsplus.com/tutorials/text-effects-tutorials/stitched-denim-text-effect/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2f8dzk2mhcqts.cloudfront.net/0769_Two_Face/preview.jpg" alt="Create a &#8220;Two-Faced&#8221; Digital Painting in Photoshop" width="200" height="200" /></div><h4><a
href='http://psd.tutsplus.com/tutorials/painting/two-faced-digital-painting/'>Create a &#8220;Two-Faced&#8221; Digital Painting in Photoshop</a></h4><p>Creating a nice character painting in Photoshop can be a difficult but rewarding task. In this tutorial, we will explain how to create a classic Batman villain in Photoshop. Let&#8217;s get started!</p><p><a
href='http://psd.tutsplus.com/tutorials/painting/two-faced-digital-painting/'>Visit Article</a></p></li></ul><hr
/><h2>Nettuts+ — Web Development Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2144_Bower/preview.jpeg" alt="Meet Bower: A Package Manager For The Web" width="200" height="200" /></div><h4><a
href='http://net.tutsplus.com/tutorials/tools-and-tips/meet-bower-a-package-manager-for-the-web/'>Meet Bower: A Package Manager For The Web</a></h4><p>As the web platform has matured, the tools for managing our projects, too, have matured. In this tutorial, I&#8217;ll introduce you to one of these tools that makes managing the dependencies of your project considerably easier: <a
href="http://twitter.github.com/bower/" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','twitter.github.com']);">Bower</a>.</p><p><a
href='http://net.tutsplus.com/tutorials/tools-and-tips/meet-bower-a-package-manager-for-the-web/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2142_MakeJSTestingFunWithTestem/make-javascript-testing-fun-with-testem.jpg" alt="Make JavaScript Testing Fun With Testem" width="200" height="200" /></div><h4><a
href='http://net.tutsplus.com/tutorials/javascript-ajax/make-javascript-testing-fun-with-testem/'>Make JavaScript Testing Fun With Testem</a></h4><p>JavaScript testing is a sensitive subject. Some developers are huge advocates of it (including myself), while others don&#8217;t see the need or benefit. One huge barrier is the simple fact that it can sometimes take a considerable amount of setup to get up and running. The longer it takes, the more likely it is that the developer simply won&#8217;t bother. That&#8217;s why <a
href="https://github.com/airportyh/testem" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','github.com']);">Testem</a> is so fantastic; it makes testing as effortless as possible, and, more importantly, fun!<br
/> <span
id="more-27738"></span></p><p><a
href='http://net.tutsplus.com/tutorials/javascript-ajax/make-javascript-testing-fun-with-testem/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2132_TDDPHP/introduction.jpg" alt="" width="200" height="200" /></div><h4><a
href='http://net.tutsplus.com/sessions/test-driven-php/'>Test Driven PHP Session</a></h4><p>Let’s be honest: the PHP community hasn’t been as quick to the test-driven development scene as other communities, such as those around the Ruby and Python languages. We hope to help change that on Nettuts+! In this session, you’ll learn both why and how to test-drive your applications using the fantastic PHPUnit. Ready?<br
/> <span
id="more-27738"></span></p><p><a
href='http://net.tutsplus.com/sessions/test-driven-php/'>Visit Article</a></p></li></ul><hr
/><h2>Vectortuts+ — Illustrator Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://dsmy2muqb7t4m.cloudfront.net/articles/2012/article_bad_logo/preview.jpg" alt="Stop Making Bad Logos" width="200" height="200" /></div><h4><a
href='http://vector.tutsplus.com/articles/theory/stop-making-bad-logos/'>Stop Making Bad Logos</a></h4><p>There&#8217;s article after article on websites that talk bout how to make a great logo. But If you&#8217;re a logo machine, and you&#8217;ve been doing it for a long time, chances are that you&#8217;ve developed some pretty awful habits. How do I know this? Because I suffered from some of the same habits I&#8217;m about to talk about. A true master of logo creation will refine their work on every project, forcing themselves to get better with each design. It all boils down to a few key things to avoid when you&#8217;re creating a logo. While you can take a stab at selling generic logos on places like GraphicRiver, you&#8217;ll do your best work when you deeply understand your clients and their company.</p><p><a
href='http://vector.tutsplus.com/articles/theory/stop-making-bad-logos/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://dsmy2muqb7t4m.cloudfront.net/tuts/000-2012/564_geometric_portrait/Final_Image_PVW_Self_Portrait.jpg" alt="How to Create a Self Portrait in a Geometric Style" width="200" height="200" /></div><h4><a
href='http://vector.tutsplus.com/tutorials/illustration/how-to-create-a-self-portrait-in-a-geometric-style/'>How to Create a Self Portrait in a Geometric Style</a></h4><p>In this tutorial we are going to talk about how to create an illustrated self portrait in a geometric based style. We are going to work from a photograph of ourselves as the base of the illustration, then drawing the sketch and to the final piece, so lets get started.</p><p><a
href='http://vector.tutsplus.com/tutorials/illustration/how-to-create-a-self-portrait-in-a-geometric-style/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://dsmy2muqb7t4m.cloudfront.net/tuts/000-2012/555_paisley/images/preview.jpg" alt="Creating Paisley Graphic Styles with Scatter Brushes and Recolor Artwork" width="200" height="200" /></div><h4><a
href='http://vector.tutsplus.com/tutorials/tools-tips/creating-paisley-graphic-styles-with-scatter-brushes-and-recolor-artwork/'>Creating Paisley Graphic Styles with Scatter Brushes and Recolor Artwork</a></h4><p>In today&#8217;s tutorial I&#8217;m going to show you how to create a series of Paisley inspired Graphic Styles using Scatter Brushes and the Appearance panel. Once done, I&#8217;ll show you how to create additional styles simply by using Recolor Artwork. This is a great tutorial for beginners as there is no Pen Tool (P) involved. So let&#8217;s begin!</p><p><a
href='http://vector.tutsplus.com/tutorials/tools-tips/creating-paisley-graphic-styles-with-scatter-brushes-and-recolor-artwork/'>Visit Article</a></p></li></ul><hr
/><h2>Webdesigntuts+ — Web Design Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d3pr5r64n04s3o.cloudfront.net/tuts/397_performance/tutimages/preview.png" alt="Best Practices for Increasing Website Performance" width="200" height="200" /></div><h4><a
href='http://webdesign.tutsplus.com/tutorials/workflow-tutorials/best-practices-for-increasing-web-site-performance/'>Best Practices for Increasing Website Performance</a></h4><p>It&#8217;s a no-brainer: well performing websites enjoy higher visitor engagement, retention and conversion. Given how fickle users can be, plus the fact that mobile devices are very significant these days, never before has the speed of websites been so important! In this article I&#8217;m going to highlight ways in which you can improve the performance of your own sites.</p><p><a
href='http://webdesign.tutsplus.com/tutorials/workflow-tutorials/best-practices-for-increasing-web-site-performance/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3pr5r64n04s3o.cloudfront.net/articles/105_buildwindows/preview.png" alt="How They Did It: Build Windows" width="200" height="200" /></div><h4><a
href='http://webdesign.tutsplus.com/articles/general/how-they-did-it-build-windows/'>How They Did It: Build Windows</a></h4><p>Today, we&#8217;ll dive into <a
href="http://buildwindows.com" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','buildwindows.com']);">the Build Windows site</a> and look at the practical code philosophies, tools, and strategies used by this highly trafficked, highly praised conference landing page. We&#8217;ll get into the nitty gritty, but we will also be covering some things from a mile-high perspective.</p><p><a
href='http://webdesign.tutsplus.com/articles/general/how-they-did-it-build-windows/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3pr5r64n04s3o.cloudfront.net/tuts/391_checkboxes/preview.png" alt="Quick Tip: Easy CSS3 Checkboxes and Radio Buttons" width="200" height="200" /></div><h4><a
href='http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/quick-tip-easy-css3-checkboxes-and-radio-buttons/'>Quick Tip: Easy CSS3 Checkboxes and Radio Buttons</a></h4><p>Ever wondered how to style checkboxes and radio buttons, but without JavaScript? Thanks to CSS3 you can!</p><p><a
href='http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/quick-tip-easy-css3-checkboxes-and-radio-buttons/'>Visit Article</a></p></li></ul><hr
/><h2>Phototuts+ — Photography Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d2f29brjr0xbt3.cloudfront.net/984_jackolantern/preview.jpg" alt="How to Make Fantastically Fun Jack &#8216;O Lantern Photos" width="200" height="200" /></div><h4><a
href='http://photo.tutsplus.com/articles/shooting-articles/how-to-make-fantastically-fun-jack-o-lantern-photos/'>How to Make Fantastically Fun Jack &#8216;O Lantern Photos</a></h4><p>&#8220;Trick or treat!&#8221; Halloween is knocking on the door. It is a very popular holiday in many countries. It brings the spirit of mystic, fear, magic and fairy. Halloween can be a great inspiration for shooting some beautiful lights -&#8221; all those jack-o-lanterns and candles.<span
id="more-10419"></span></p><p><a
href='http://photo.tutsplus.com/articles/shooting-articles/how-to-make-fantastically-fun-jack-o-lantern-photos/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/photo.tutsplus.com/Diana%20Eftaiha/2012/10/08/Adding-a-sense-of-depth-to-your-photos.jpg" alt="How to Create a Sense of Depth to Your Photos" width="200" height="200" /></div><h4><a
href='http://photo.tutsplus.com/articles/composition-articles/how-to-create-a-sense-of-depth-to-your-photos/'>How to Create a Sense of Depth to Your Photos</a></h4><p>Today we will take a look at how to add some sense of depth to your photographs and thus make them become alive and more interesting to the viewer. By making use of some simple but very effective factors that can be applied at the time of exposure, you can make a your picture pop. Today, we&#8217;ll talk about perspective, depth of field, and framing.</p><p><a
href='http://photo.tutsplus.com/articles/composition-articles/how-to-create-a-sense-of-depth-to-your-photos/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/photo.tutsplus.com/Rob%20Taylor/2012/10/03/preview.jpg" alt="Dealing With Foliage: Green and Yellow Saturation" width="200" height="200" /></div><h4><a
href='http://photo.tutsplus.com/articles/dealing-with-foliage-green-and-yellow-saturation/'>Dealing With Foliage: Green and Yellow Saturation</a></h4><p>I&#8217;ve noticed around the internet that a great many people struggle with foliage. A large number of people don&#8217;t even seem to notice that there&#8217;s an issue, which is unfortunately falsely backed up by the legions of commenters trying to be nice rather than truthful. The problem persists for all levels of photographers, from year one amateurs to multi-year pros.<span
id="more-10127"></span></p><p><a
href='http://photo.tutsplus.com/articles/dealing-with-foliage-green-and-yellow-saturation/'>Visit Article</a></p></li></ul><hr
/><h2>Cgtuts+ — Computer Graphics Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d2d04grx5ahzvh.cloudfront.net/455_iPhone_4S_PT4/iPhone_Thumb.jpg" alt="Creating The iPhone 4S In 3D Studio Max, Part 4 Texturing &#038; Rendering with V-Ray" width="200" height="200" /></div><h4><a
href='http://cg.tutsplus.com/tutorials/autodesk-3d-studio-max/creating-the-iphone-4s-in-3d-studio-max-part-4-texturing-rendering-with-v-ray/'>Creating The iPhone 4S In 3D Studio Max, Part 4 Texturing &#038; Rendering with V-Ray</a></h4><p>In the fourth part of the iPhone series we&#8217;ll begin creating textures and the many shaders needed for our model. While most will be procedural materials, a few of the elements do require image based textures, so we&#8217;ll first tackle the uvmapping on these elements. We&#8217;ll then move on and construct a studio lighting rig using V-Ray lights and introduce image based lighting to the scene. Along the way we&#8217;ll rely heavily on the power of V-Ray&#8217;s RT engine to fine tune our materials, lighting and render settings to balance the scene and achieve the look we&#8217;re after for our final render.</p><p><a
href='http://cg.tutsplus.com/tutorials/autodesk-3d-studio-max/creating-the-iphone-4s-in-3d-studio-max-part-4-texturing-rendering-with-v-ray/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d2d04grx5ahzvh.cloudfront.net/451_Maya_IceCream_PT1/Thumb_PT1.png" alt="Creating an Ice Cream Bar Animation with Maya, RealFlow And AE &#8211; Part 1" width="200" height="200" /></div><h4><a
href='http://cg.tutsplus.com/tutorials/autodesk-maya/creating-an-ice-cream-bar-animation-with-maya-realflow-and-ae-part-1/'>Creating an Ice Cream Bar Animation with Maya, RealFlow And AE &#8211; Part 1</a></h4><p>Hey folks, in this three part tutorial spanning both Cgtuts+ and<a
href="http://ae.tutsplus.com/" > Aetuts+</a>, we are going to create liquid chocolate pouring over a branded ice cream bar. To achieve this we will use Maya for mashing and rendering. RealFlow for the chocolate simulation. And finally in After Effects we&#8217;ll create the chocolate chunks and glow streaks swoosh, as well as the final compositing.<span
id="more-17866"></span></p><p><a
href='http://cg.tutsplus.com/tutorials/autodesk-maya/creating-an-ice-cream-bar-animation-with-maya-realflow-and-ae-part-1/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tutsplus.s3.amazonaws.com/tutspremium/3d-graphics/92_Faux_Energy_Drink/Thumb.jpg" alt="Create a High Impact Faux Energy Drink Ad with 3D Studio Max, Cinema 4D &#038; AE &#8211; Tuts+ Premium" width="200" height="200" /></div><h4><a
href='http://cg.tutsplus.com/tutorials/maxon-cinema-4d/create-a-high-impact-faux-energy-drink-ad-with-3d-studio-max-cinema-4d-ae-tuts-premium/'>Create a High Impact Faux Energy Drink Ad with 3D Studio Max, Cinema 4D &#038; AE &#8211; Tuts+ Premium</a></h4><p>In this tutorial we are going to create from start to finish an interesting short four shot ad cut for a fake energy drink &rsquo;Envato Energy&#8221;. This will give you some guidance on how to create something similar for a real life project.</p><p><a
href='http://cg.tutsplus.com/tutorials/maxon-cinema-4d/create-a-high-impact-faux-energy-drink-ad-with-3d-studio-max-cinema-4d-ae-tuts-premium/'>Visit Article</a></p></li></ul><hr
/><h2>Aetuts+ — After Effects Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d3gphd0pfuxn95.cloudfront.net/816_groundbreak/thumbnail.jpg" alt="Create A Ground Breaking Pavement Crack Simulation" width="200" height="200" /></div><h4><a
href='http://ae.tutsplus.com/tutorials/vfx/create-a-ground-breaking-pavement-crack-simulation/'>Create A Ground Breaking Pavement Crack Simulation</a></h4><p>In this tutorial we will learn how to properly create a good workflow between After Effects and Cinema 4D. In the process we are going to take a look at how to create your own custom ground cracking overlays for compositing.<br
/> <span
id="more-22265"></span></p><p><a
href='http://ae.tutsplus.com/tutorials/vfx/create-a-ground-breaking-pavement-crack-simulation/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3gphd0pfuxn95.cloudfront.net/814_coverflow/cover_flow_thumbnail.jpg" alt="How To Use The Amazing Free New Preset &#8220;Cover Flow&#8221;" width="200" height="200" /></div><h4><a
href='http://ae.tutsplus.com/tutorials/workflow/how-to-use-the-amazing-free-new-preset-cover-flow/'>How To Use The Amazing Free New Preset &#8220;Cover Flow&#8221;</a></h4><p>Cover Flow is a preset for AE to create the <a
href="http://en.wikipedia.org/wiki/Cover_Flow" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','en.wikipedia.org']);">classic flowing cover effect</a> best known from iTunes. On top of that it has several options to change the result like adding randomness to the position of the layers, adding blur to fake a depth of field and so on. Today we&#8217;ll walk you through how to install and use this tool.</p><p><a
href='http://ae.tutsplus.com/tutorials/workflow/how-to-use-the-amazing-free-new-preset-cover-flow/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3gphd0pfuxn95.cloudfront.net/815_batman/thumbnailbatman.jpg" alt="Illustrator to After Effects Relation-tips &#8211; Batman Vector Animation" width="200" height="200" /></div><h4><a
href='http://ae.tutsplus.com/tutorials/motion-graphics/illustrator-to-after-effects-relation-tips-batman-vector-animation/'>Illustrator to After Effects Relation-tips &#8211; Batman Vector Animation</a></h4><p>This the first tutorial of a four part series where we are going to show some of the most common and widely used effects for After Effects.</p><p><a
href='http://ae.tutsplus.com/tutorials/motion-graphics/illustrator-to-after-effects-relation-tips-batman-vector-animation/'>Visit Article</a></p></li></ul><hr
/><h2>Audiotuts+ — Audio &amp; Production Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://d3vvl31cy8gagb.cloudfront.net/779_livesound/preview.jpg" alt="How to Enhance a Live, Out-of-the-Mixer Concert Recording" width="200" height="200" /></div><h4><a
href='http://audio.tutsplus.com/tutorials/mixing-mastering/how-to-enhance-a-live-out-of-the-mixer-concert-recording/'>How to Enhance a Live, Out-of-the-Mixer Concert Recording</a></h4><p>I was playing at a concert recently where I had the fortune on getting my hands on a 2-track recording out of the FOH mixer. I playing at a festival and all the stages recorded the acts, giving them a CD at the end of their set. Usually, a recording such as this is done straight out of the L/R OUT of the mixer. All the channels of the mixer are fed to the stereo out that&#8217;s fed into a stereo recorder. The recording is then burned onto a CD for the bands to listen to.<br
/> <span
id="more-15067"></span></p><p><a
href='http://audio.tutsplus.com/tutorials/mixing-mastering/how-to-enhance-a-live-out-of-the-mixer-concert-recording/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3vvl31cy8gagb.cloudfront.net/784_synth/preview.jpg" alt="Essential Subtractive Synthesis: Envelopes" width="200" height="200" /></div><h4><a
href='http://audio.tutsplus.com/tutorials/sound-design/essential-subtractive-synthesis-envelopes/'>Essential Subtractive Synthesis: Envelopes</a></h4><p>This is a series of basic synthesis workshops. We assume you&#8217;re not entirely new to synthesizers, but you&#8217;re not an expert either. Today we look at envelopes.</p><p><a
href='http://audio.tutsplus.com/tutorials/sound-design/essential-subtractive-synthesis-envelopes/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://d3vvl31cy8gagb.cloudfront.net/782_listening/preview.jpg" alt="Essential Listening &#8211; Getting Critical" width="200" height="200" /></div><h4><a
href='http://audio.tutsplus.com/articles/general/essential-listening-getting-critical/'>Essential Listening &#8211; Getting Critical</a></h4><p>Welcome back for another round of Essential Listening. Last time we took a look at some of the big albums of all time and how the mixes were so different, but at the same time all great. And while we will certainly revisit looking at some classic songs and albums from an engineering standpoint down the road, today is all about improving your critical listening skills.</p><p><a
href='http://audio.tutsplus.com/articles/general/essential-listening-getting-critical/'>Visit Article</a></p></li></ul><hr
/><h2>Wptuts+ — WordPress Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://tutsplus.s3.amazonaws.com/writefortuts/writefortuts.jpg" alt="WANTED: WordPress Professionals With a Passion for Education. Enquire Within." width="200" height="200" /></div><h4><a
href='http://wp.tutsplus.com/articles/news/wanted-wordpress-professionals-with-a-passion-for-education-enquire-within/'>WANTED: WordPress Professionals With a Passion for Education. Enquire Within.</a></h4><p><strong>Are you an experienced WordPress professional with a desire to educate others on standards and best practices?</strong> If so, we&#8217;d like to speak with you about writing for Wptuts+ 1-4 times per month. We&#8217;d like you to submit at least one article a month, and you&#8217;re free to choose your topics, as long as they appeal to our audience. <strong>This is a paid job.</strong> If you&#8217;re interesting in helping educate others in The WordPress Way, read on.<span
id="more-27549"></span></p><p><a
href='http://wp.tutsplus.com/articles/news/wanted-wordpress-professionals-with-a-passion-for-education-enquire-within/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/wp.tutsplus.com/Japh/2012/10/12/preview.png" alt="Building a Simple Announcements Plugin for WordPress" width="200" height="200" /></div><h4><a
href='http://wp.tutsplus.com/tutorials/plugins/building-a-simple-announcements-plugin-for-wordpress/'>Building a Simple Announcements Plugin for WordPress</a></h4><p>Let&#8217;s say that you&#8217;re a launching new product, giving away freebies or organizing an event. How do you deliver the message to your readers? Popular choice is to display a modal dialog in a lightbox, thus forcing the user to take notice. But there&#8217;s another, less obtrusive, yet still effective way, to get a user&#8217;s attention. In this tutorial we&#8217;ll be creating a plugin that displays custom site-wide announcements across the top of the page, with the ability to schedule messages to appear between two given dates.<span
id="more-27661"></span></p><p><a
href='http://wp.tutsplus.com/tutorials/plugins/building-a-simple-announcements-plugin-for-wordpress/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/wp.tutsplus.com/Japh/2012/10/17/The-Beginners-Guide-To-WordPress-Actions-and-Filters.jpg" alt="The Beginner&#8217;s Guide to WordPress Actions and Filters" width="200" height="200" /></div><h4><a
href='http://wp.tutsplus.com/tutorials/the-beginners-guide-to-wordpress-actions-and-filters/'>The Beginner&#8217;s Guide to WordPress Actions and Filters</a></h4><p>When it comes to professional WordPress development, it&#8217;s imperative that developers understand both actions and filters &#8211; that is, it&#8217;s important to understand WordPress hooks.</p><p><a
href='http://wp.tutsplus.com/tutorials/the-beginners-guide-to-wordpress-actions-and-filters/'>Visit Article</a></p></li></ul><hr
/><h2>Mobiletuts+ — Mobile Development Tutorials</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="https://d339vfjsz5zott.cloudfront.net/iPhone5_Display/iPhone5-Display_iOS6.png" alt="Working with the iPhone 5 Display" width="200" height="200" /></div><h4><a
href='http://mobile.tutsplus.com/tutorials/iphone/working-with-the-iphone-5-display/'>Working with the iPhone 5 Display</a></h4><p>This tutorial will review the steps necessary to ensure that your iOS apps will continue to look great when displayed on the new iPhone 5 screen.<br
/> <span
id="more-12938"></span></p><p><a
href='http://mobile.tutsplus.com/tutorials/iphone/working-with-the-iphone-5-display/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="https://d339vfjsz5zott.cloudfront.net/miscfiles/previews/iOS-Drawing_Preview.png" alt="Smooth Freehand Drawing on iOS" width="200" height="200" /></div><h4><a
href='http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_freehand-drawing/'>Smooth Freehand Drawing on iOS</a></h4><p>This tutorial will teach you how to implement an advanced drawing algorithm for smooth, freehand drawing on iOS devices. Read on!<br
/> <span
id="more-13164"></span></p><p><a
href='http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_freehand-drawing/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="https://d339vfjsz5zott.cloudfront.net/Android-ASCII-Editor/Android-ASCII_Preview.png" alt="Build an ASCII Art Editor: Interface Setup" width="200" height="200" /></div><h4><a
href='http://mobile.tutsplus.com/tutorials/android/build-an-ascii-art-editor-interface-setup/'>Build an ASCII Art Editor: Interface Setup</a></h4><p>The Android platform offers a wide range of storage options for use within your apps. In this tutorial series, we are going to explore some of the data storage facilities provided by the Android SDK by building a simple project: an ASCII art editor.<br
/> <span
id="more-12791"></span></p><p><a
href='http://mobile.tutsplus.com/tutorials/android/build-an-ascii-art-editor-interface-setup/'>Visit Article</a></p></li></ul><hr
/><h2>Gamedevtuts+ — Game Development</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Tomislav%20Podhraski/2012/10/06/Preview2.png" alt="Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders" width="200" height="200" /></div><h4><a
href='http://gamedev.tutsplus.com/tutorials/implementation/create-a-glowing-flowing-lava-river-using-bezier-curves-and-shaders/'>Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders</a></h4><p>Most of the time, using conventional graphic techniques is the right way to go. Sometimes, though, experimentation and creativity at the fundamental levels of an effect can be beneficial to the style of the game, making it stand out more. In this tutorial I&#8217;m going to show you how to create an animated 2D lava river using Bézier curves, custom textured geometry and vertex shaders.<span
id="more-919"></span></p><p><a
href='http://gamedev.tutsplus.com/tutorials/implementation/create-a-glowing-flowing-lava-river-using-bezier-curves-and-shaders/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://gamedevtuts.s3.amazonaws.com/039_howToLearnUnity/How_To_Learn_Unity.jpg" alt="How to Learn Unity" width="200" height="200" /></div><h4><a
href='http://gamedev.tutsplus.com/articles/how-to-learn/how-to-learn-unity/'>How to Learn Unity</a></h4><p>Unity is a feature rich, fully integrated development engine for the creation of interactive 3D content. You want to make 3D games? Unity&#8217;s got you covered. In this article we&#8217;ll share books, tutorials and suggestions for getting to grips with Unity.<span
id="more-1333"></span></p><p><a
href='http://gamedev.tutsplus.com/articles/how-to-learn/how-to-learn-unity/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/gamedev.tutsplus.com/Paul%20Suddaby/2012/10/23/Heavy_Rain_Logo.jpg" alt="How Heavy Rain&#8217;s Narrative Is Strengthened by Its Gameplay" width="200" height="200" /></div><h4><a
href='http://gamedev.tutsplus.com/articles/game-design-articles/how-heavy-rains-narrative-is-strengthened-by-its-gameplay/'>How Heavy Rain&#8217;s Narrative Is Strengthened by Its Gameplay</a></h4><p>Heavy Rain received immense critical praise for being an experience that elevated video game storytelling to a new level. In this article, we&#8217;ll look at why that is and what we can learn from it.</p><p><a
href='http://gamedev.tutsplus.com/articles/game-design-articles/how-heavy-rains-narrative-is-strengthened-by-its-gameplay/'>Visit Article</a></p></li></ul><hr
/><h2>Mactuts+ — Mac &#038; OS X</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/mac.tutsplus.com/Josh%20Johnson/2012/10/02/geektool-f.png" alt="5 Ways to Make Your Mac&#8217;s Desktop Better with GeekTool" width="200" height="200" /></div><h4><a
href='http://mac.tutsplus.com/tutorials/customization/5-ways-to-make-your-macs-desktop-better-with-geektool/'>Ways to Make Your Mac&#8217;s Desktop Better with GeekTool</a></h4><p>GeekTool is an amazing free app that is a bit like Dashboard for the super nerdy. It allows you to place functional widgets, called &#8220;Geeklets,&#8221; right on top of your desktop, so you can always see them. Implementation can be a little tricky though so this tutorial will walk you through five different ways to use Geeklets to enhance your desktop experience.</p><p><a
href='http://mac.tutsplus.com/tutorials/customization/5-ways-to-make-your-macs-desktop-better-with-geektool/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://tuts-authors.s3.amazonaws.com/mac.tutsplus.com/John%20Winter/2012/09/13/tlphn-icon.png" alt="How to Set Up and Use VoIP on Your Mac" width="200" height="200" /></div><h4><a
href='http://mac.tutsplus.com/tutorials/productivity/how-to-set-up-and-use-voip-on-your-mac/'>How to Set Up and Use VoIP on Your Mac</a></h4><p>With the advent of faster broadband, the viability of using your data connection for voice communications has become increasingly reliable. VoIP has lower startup and ongoing costs than traditional, fixed-line telephones and has a wealth of flexible features that are often additional cost options from your dinosaur-era fixed-line phone network.  If you are a freelancer, a business owner, or even just home user who requires a separate telephone from your home number, then VoIP is for you.</p><p><a
href='http://mac.tutsplus.com/tutorials/productivity/how-to-set-up-and-use-voip-on-your-mac/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="https://tuts-authors.s3.amazonaws.com/mac.tutsplus.com/John%20Pavlovits/2012/09/02/Terminal%20Tutorial%20Icon.png" alt="Quick Tip: Trick Out Your Mac with Terminal" width="200" height="200" /></div><h4><a
href='http://mac.tutsplus.com/tutorials/terminal/quick-tip-trick-out-your-mac-with-terminal/'>Quick Tip: Trick Out Your Mac with Terminal</a></h4><p>The Mac OS X operating system is already really sleek, but we&#8217;re going to look at how to use terminal to activate some cool hidden settings that will make your Mac even better. The terminal tricks I&#8217;ll be showing you range from adding spaces to your dock to freeing your Dashboard widgets from the Dashboard. So let&#8217;s get started!<br
/> <span
id="more-31318"></span></p><p><a
href='http://mac.tutsplus.com/tutorials/terminal/quick-tip-trick-out-your-mac-with-terminal/'>Visit Article</a></p></li></ul><hr
/><h2>FreelanceSwitch — Freelance Jobs &#038; Information</h2><ul
class="webroundup"><li
class='clear'><div> <img
src="http://freelanceswitch.com/wp-content/uploads/2012/10/Payday-dollars-hand-businessman.jpg" alt="" width="200" height="200" /></div><h4><a
href='http://freelanceswitch.com/the-business-of-freelancing/raise-your-freelance-rates/'>How to Raise Your Freelance Pay Rates in the Next 60 Days</a></h4><p>Freelancers interested in earning big should always be looking for opportunities to raise rates. Luckily, if you’re reading this in the fall, you’re at one of the easiest times of year to get a raise.<br
/> I’ll explain why in a minute. <br
/> But first, let’s talk a little economic reality about why you need to get aggressive about asking for a raise.</p><p><a
href='http://freelanceswitch.com/the-business-of-freelancing/raise-your-freelance-rates/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://freelanceswitch.s3.amazonaws.com/previewimages/2012/How-to-Set-Up-Your-LinkedIn-Profile-Freelancer-Guide.png" alt="" width="200" height="200" /></div><h4><a
href='http://freelanceswitch.com/freelance-marketing/set-up-your-linkedin-profile/'>How to Set Up Your LinkedIn Profile: A Freelancer’s Guide</a></h4><p>LinkedIn makes sense for professionals, but what about for freelancers?<br
/> In my experience, LinkedIn is an important tool in my marketing toolbox. Being on LinkedIn allows me to showcase my skills and experience. Additionally, LinkedIn is a networking platform, which makes it perfect for finding prospects, hooking up with new clients or reconnecting with past clients.</p><p><a
href='http://freelanceswitch.com/freelance-marketing/set-up-your-linkedin-profile/'>Visit Article</a></p></li><li
class='clear'><div> <img
src="http://freelanceswitch.s3.amazonaws.com/previewimages/2012/How-Write-Effective-Freelancer-About-Page.png" alt="" width="200" height="200" /></div><h4><a
href='http://freelanceswitch.com/freelancing-essentials/freelancer-about-page/'>How to Write an Effective Freelancer About Page</a></h4><p>The most visited page on most websites is the about page. That holds particularly true for freelancers — on my site, almost half of my visitors wind up there. That’s because a client looking to hire some help wants to know exactly who he’ll be working with. <br
/> When he’s found you online, he’s not going to have a sense of who you are and why you’re worth your rates until he’s found out more. Your about page is the easiest way to do so.<br
/> <span
id="more-31318"></span></p><p><a
href='http://freelanceswitch.com/freelancing-essentials/freelancer-about-page/'>Visit Article</a></p></li></ul>
<p><a href="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/0/da"><img src="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/1/da"><img src="http://feedads.g.doubleclick.net/~a/37wU7YCCJ3jkJMmppUY_pjQCJEI/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=n3HCLGxAt4Q:ZXavmXnxJpA:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=n3HCLGxAt4Q:ZXavmXnxJpA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=n3HCLGxAt4Q:ZXavmXnxJpA:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=n3HCLGxAt4Q:ZXavmXnxJpA:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/n3HCLGxAt4Q" height="1" width="1"/>";s:14:"date_timestamp";i:1352126964;}i:7;a:13:{s:5:"title";s:42:"The Whens and Whys for PHP Design Patterns";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/QErzWmd5JXI/";s:8:"comments";s:90:"http://net.tutsplus.com/tutorials/php/the-whens-and-whys-for-php-design-patterns/#comments";s:7:"pubdate";s:31:"Mon, 05 Nov 2012 14:48:53 +0000";s:2:"dc";a:1:{s:7:"creator";s:12:"Patkos Csaba";}s:8:"category";s:18:"PHPdesign patterns";s:4:"guid";s:32:"http://net.tutsplus.com/?p=27862";s:11:"description";s:25462:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27862&c=1475446250' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27862&c=1475446250' border='0' alt='' /></a><p>There are plenty of articles that explain what design patterns are, and how to implement them; the web doesn&#8217;t need yet another one of those articles! Instead, in this article, we will more discuss the <i>when</i> and <i>why</i>, rather than the <i>which</i> and <i>how</i>.</p><p>I&#8217;ll present different situations and use-cases for patterns, and will also provide short definitions to help those of you who are not so familiar with these specific patterns. Let&#8217;s get started.</p><p><span
id="more-27862"></span></p><p>This article covers some of the various <i>Agile Design Patterns</i>, documented in Robert C. Martin&#8217;s books. These patterns are modern adaptations of the original design patterns defined and documented by <i><a
href="http://en.wikipedia.org/wiki/Design_Patterns" title="GoF: Design Patterns" target="_blank">The Gang of Four</a></i> in 1994. Martin&#8217;s patterns present a much more recent take on the GoF&#8217;s patterns, and they work better with modern programming techniques and problems. In fact, about 15% of the original patterns were replaced with newer patterns, and the remaining patterns were slightly modernized.</p><hr
/><h2>Let&#8217;s Start by Creating Some Objects</h2><h3>Use a Factory Pattern</h3><p>The factory pattern was invented to help programmers organize the information related to object creation. Objects sometimes have lot of constructor parameters; other times, they must be populated with default information immediately after their creation. These objects should be created in factories, keeping all the information regarding their creation and initialization contained within a single place.</p><div
class="tip-shortcode"><p><strong>When</strong> Use a Factory Pattern when you find yourself writing code to gather information necessary to create objects.</p><p><strong>Why:</strong> Factories help to contain the logic of object creation in a single place. They can also break dependencies to facilitate loose coupling and dependency injection to allow for better testing.</p></div><hr
/><h2>Finding the Data We Need</h2><p>There are two frequently used patterns to retrieve information from a persistence layer or external data source.</p><h3>The Gateway Pattern</h3><p>This pattern defines a communication channel between a persistence solution and the business logic. For simpler applications, it can retrieve or recreate whole objects by itself, but object creation is the responsibility of factories in most complex applications. Gateways simply retrieve and persist raw data.</p><div
class="tip-shortcode"><p><strong>When:</strong> When you need to retrieve or persist information.</p><p><strong>Why:</strong> It offers a simple public interface for complicated persistence operations. It also encapsulates persistence knowledge and decouples business logic from persistence logic.</p></div><p>In fact, the gateway pattern is just a particular implementation of another design pattern that we&#8217;ll discuss shortly: the adapter pattern.</p><h3>Go with the Proxy</h3><p>There are times when you can not (or do not want to) expose the knowledge of the persistence layer to your business classes. The proxy pattern is a good way to fool your business classes into thinking they are using already existing objects.</p><div
class="tip-shortcode"><p><strong>When:</strong> You have to retrieve information from a persistence layer or external source, but don&#8217;t want your business logic to know this.</p><p><strong>Why:</strong> To offer a non-intrusive approach to creating objects behind the scenes. It also opens the possibility to retrieve these object on the fly, lazily, and from different sources.</p></div><p>A proxy effectively implements the same interface as a real object and mimics its functionality. The business logic simply uses it as if it were a real object, but in fact, the proxy creates the object if one doesn&#8217;t exist.</p><blockquote
class="pullquote"><p>The active object pattern also played a part in early multi-tasking systems.</p></blockquote><p>Okay, okay. That great and all, but how can we find the objects that we need to create?</p><h3>Ask a Repository</h3><p>The repository pattern is very useful for implementing search methods and mini-query languages. It takes these queries and uses a gateway to obtain the data for a factory to produce the objects you need.</p><p>The repository pattern is different from the other patterns; it exists as part of Domain Driven Design (DDD), and is not included as part of Robert C. Martin&#8217;s book.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to create multiple objects based on search criteria, or when you need to save multiple objects to the persistence layer.</p><p><strong>Why:</strong> To let clients that need specific objects to work with a common and well isolated query and persistence language. It removes even more creation-related code from the business logic.</p></div><p>But what if the repository cannot find the objects? One option would be to return a <code>NULL</code> value, but doing so has two side effects:</p><ul><li>It throws a <i>refused bequest</i> if you try to call a method on such an object.</li><li>It forces you to include numerous null checks (<code>if(is_null($param)) return;</code>) in your code.</li></ul><p>A better approach is to return a <code>null</code> object.</p><h3>The Null Object Pattern</h3><p>A null object implements the same interface of your other objects, but the object&#8217;s members return a neutral value. For example, a method that returns a string would return an empty string; another member returning a numeric value would return zero. This forces you to implement methods that do not return meaningful data, but you can use these objects without worrying about refused bequest or littering your code with null checks.</p><div
class="tip-shortcode"><p><strong>When:</strong> You frequently check for <code>null</code> or you have refused bequests.</p><p><strong>Why:</strong> It can add clarity to your code and forces you to think more about the behavior of your objects.</p></div><p>It&#8217;s not unusual to call many methods on an object before it can do its job. There are situations when you must prepare an object after its creation before you can truly use it. This leads to code duplication when creating those objects in different places.</p><h3>You Need the Command Pattern</h3><div
class="tip-shortcode"><p><strong>When:</strong> When you have to perform many operations to prepare objects for use.</p><p><strong>Why:</strong> To move complexity from the consuming code to the creating code.</p></div><p>This sounds good, doesn&#8217;t it? In fact, it is quite useful in many situations. The command pattern is widely used for implementing transactions. If you add a simple <code>undo()</code> method to a command object, it can track all the undo transactions it performed and reverse them if necessary.</p><p>So now you have ten (or more) command objects, and you want them running concurrently. You can gather them into an active object.</p><h3>The Active Object</h3><p>The simple and interesting active object has only one responsibility: keep a list of command objects and run them.</p><div
class="tip-shortcode"><p><strong>When:</strong> Several similar objects have to execute with a single command.</p><p><strong>Why:</strong> It forces clients to perform a single task and affect multiple objects.</p></div><p>An active object removes each command from its list after the command&#8217;s execution; meaning, you can execute the command only once. Some real world examples of an active object are:</p><blockquote
class="pullquote"><p>Design patterns are here to solve problems.</p></blockquote><ul><li><strong>Shopping Cart</strong> &#8211; Executing a <code>buy()</code> command on each product removes them from the cart.</li><li><strong>Financial Transactions</strong> &#8211; Grouping transactions into a single list and executing them with a simple call to the list manager&#8217;s active object would remove the transactions from the queue.</li></ul><p>The active object pattern also played a part in early multi-tasking systems. Each object inside an active object would keep a reference to the active object. They would execute a portion of their jobs and then put themselves back into the queue. Even in today&#8217;s systems, you can use an active object to let other objects work while you wait for a response from another application.</p><hr
/><h2>Reusability</h2><p>I am positive that you&#8217;ve heard the big promise of object oriented programming: code reuse. Early adopters of OOP envisioned using universal libraries and classes in millions of different projects. Well, it never happened.</p><h3>Make Some Template Methods Instead</h3><p>This pattern allows for the partial reuse of code. It&#8217;s practical with multiple algorithms which only slightly differ from one another.</p><div
class="tip-shortcode"><p><strong>When:</strong> Eliminate duplication in a simple way.</p><p><strong>Why:</strong> There is duplication and flexibility is not a problem.</p></div><p>But flexibility is nice. What if I really need it?</p><h3>It&#8217;s Time For a Strategy</h3><div
class="tip-shortcode"><p><strong>When:</strong> Flexibility and reusability is more important than simplicity.</p><p><strong>Why:</strong> Use it to implement big, interchangeable chunks of complicated logic, while keeping a common algorithm signature.</p></div><p>For example, you can create a generic <code>Calculator</code> and then use different <code>ComputationStrategy</code> objects to perform the calculations. This is a moderately used pattern, and it is most powerful when you have to define many conditional behaviors.</p><hr
/><h2>Discover-ability</h2><p>As projects grow, it becomes increasingly difficult for external users to access our application. That&#8217;s one reason to offer a well-defined entry point to the application or module in question. Other such reasons may include the desire to conceal the module&#8217;s internal workings and structure.</p><h3>Present a Facade</h3><p>A facade is essentially an API &#8211; a nice and client-facing interface. When a client calls one of these nice methods, the facade delegates a series of calls to the classes it hides in order to provide the client with the required information or desired result.</p><div
class="tip-shortcode"><p><strong>When:</strong> To simplify your API or intentionally conceal inner business logic.</p><p><strong>Why:</strong> You can control the API and the real implementations and logic independently.</p></div><p>Control is good, and many times you need to perform a task when something changes. Users have to be notified, red LEDs have to blink, an alarm has to sound&#8230; you get the idea.</p><blockquote><p> The popular <a
href="http://laravel.com">Laravel</a> framework makes excellent use of the Facade Pattern.</p></blockquote><h3>Subscribe to an Observer</h3><blockquote
class="pullquote"><p>A null object implements the same interface as your other objects.</p></blockquote><p>The observer pattern offers an easy way to monitor objects and take actions when conditions change. There are two types of observer implementations:</p><ul><li><strong>Polling</strong> &#8211; Objects accept subscribers. Subscribers observe the object and are notified on specific events. Subscribers <i>ask</i> the observed objects for more information in order to take an action.</li><li><strong>Push</strong> &#8211; Like the polling method, objects accept subscribers, and subscribers are notified when an event occurs. But when a notification happens, <i>the observer also receives a hint</i> that the observer can act on.</li></ul><div
class="tip-shortcode"><p><strong>When:</strong> To provide a notification system inside your business logic or to the outside world.</p><p><strong>Why:</strong> The pattern offers a way to communicate events to any number of different objects.</p></div><p>Use cases for this pattern are email notifications, logging daemons, or messaging systems. Of course, in real life, there are countless other ways to use it.</p><h3>Coordinate The Effects</h3><p>The observer pattern can be extended with a mediator pattern. This pattern takes two objects as parameters. The mediator subscribes itself to the first parameter, and when a change happens to the observed object, the mediator decides what to do on the second object.</p><div
class="tip-shortcode"><p><strong>When:</strong> The affected objects can not know about the observed objects.</p><p><strong>Why:</strong> To offer a hidden mechanism of affecting other objects in the system when one object changes.</p></div><hr
/><h2>Singularity</h2><p>Sometimes, you need special objects that are unique in your application, and you want to ensure that all consumers can see any change made to these objects. You also want to prevent creating multiple instances of such objects for certain reasons, like long initialization time or problems with concurrent actions to some third party libraries.</p><h3>Use a Singleton</h3><p>A singleton is an object having a private constructor and a public <code>getInstance()</code> method. This method ensures that only one instance of the object exists.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to achieve singularity and want a cross platform, lazily evaluated solution which also offers the possibility of creation through derivation.</p><p><strong>Why:</strong> To offer a single point of access when needed.</p></div><h3>Or Write a Monostate Object</h3><p>Another approach to singularity is the monostate design pattern. This solution uses a trick offered by object oriented programming languages. It has dynamic public methods which get or set the values of static private variables. This, in turn, ensures that all instances of such classes share the same values.</p><div
class="tip-shortcode"><p><strong>When:</strong> Transparency, derivabitility, and polymorphism are preferred together with singularity.</p><p><strong>Why:</strong> To hide from the users/clients the fact that the object offers singularity.</p></div><p>Pay special attention to singularity. It pollutes the global namespace and, in most cases, can be replaced with something better suited for that particular situation.</p><hr
/><h2>Controlling Different Objects</h2><blockquote
class="pullquote"><p>The repository pattern is quite useful for implementing search methods&#8230;</p></blockquote><p>So you have a switch and a light. The switch can turn the light on and off, but, now, you&#8217;ve purchased a fan and want to use your old switch with it. That&#8217;s easy to accomplish in the physical world; take the switch, connect the wires, and viola.</p><p>Unfortunately, it&#8217;s not so easy in the programming world. You have a <code>Switch</code> class and a <code>Light</code> class. If your <code>Switch</code> uses the <code>Light</code>, how could it use the <code>Fan</code>?</p><p>Easy! Copy and paste the <code>Switch</code>, and change it to use the <code>Fan</code>. But that&#8217;s code duplication; it&#8217;s the equivalent of buying another switch for the fan. You could extend <code>Switch</code> to <code>FanSwitch</code>, and use that object instead. But what if you want to use a <code>Button</code> or <code>RemoteControl</code>, instead of a <code>Switch</code>?</p><h3>The Abstract Server Pattern</h3><p>This is the simplest pattern ever invented. It only uses an interface. That&#8217;s it, but there are several different implementations.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to connect objects and maintain flexibility.</p><p><strong>Why:</strong> Because it is the simplest way to achieve flexibility, while respecting both the dependency inversion principle and the open close principle.</p></div><p>PHP is dynamically typed. This means that you can omit interfaces and use different objects in the same context &#8211; risking a refused bequest. However, PHP also allows for the definition of interfaces, and I recommend you use this great functionality to provide clarity to the intent of your source code.</p><p>But you already have a bunch of classes you want to talk to? Yes, of course. There are many libraries, third-party APIs, and other modules that one has to talk to, but this does not mean that our business logic has to know the details of such things.</p><h3>Plug in an Adapter</h3><p>The adapter pattern simply creates a correspondence between the business logic and something else. We have already seen such a pattern in action: the gateway pattern.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to create a connection with a pre-existing and potentially changing module, library, or API.</p><p><strong>Why:</strong> To allow your business logic to rely only on the public methods the adapter offers, and permit changing the other side of the adapter easily.</p></div><p>If either of the above patterns don&#8217;t fit with your situation, then you could use&#8230;</p><h3>The Bridge Pattern</h3><p>This is a very complicated pattern. I personally do not like it because it is usually easier to take a different approach. But for those special cases, when other solutions fail, you can consider the bridge pattern.</p><div
class="tip-shortcode"><p><strong>When:</strong> The adapter pattern is not enough, and you change classes on both sides of the pipe.</p><p><strong>Why:</strong> To offer increased flexibility at the cost of significant complexity.</p></div><hr
/><h2>The Composite Pattern</h2><p>Consider that you have a script with similar commands, and you want make a single call to run them. Wait! Didn&#8217;t we already see something like this earlier? The active object pattern?</p><p>Yes, yes we did. But this one is a bit different. It&#8217;s the composite pattern, and like the active object pattern, it keeps a list of objects. But calling a method on a composite object calls the same method on all of its objects without removing them from the list. The clients calling a method are thinking they are talking to a single object of that particular type, but in fact, their actions are applied to many, many objects of the same type.</p><div
class="tip-shortcode"><p><strong>When:</strong> You have to apply an action to several similar objects.</p><p><strong>Why:</strong> To reduce duplication and simplify how similar objects are called.</p></div><p>Here&#8217;s an example: you have an application that is capable of creating and placing <code>Orders</code>. Assume you have three orders: <code>$order1</code>, <code>$order2</code> and <code>$order3</code>. You could call <code>place()</code> on each of them, or you could contain those orders in a <code>$compositeOrder</code> object, and call its <code>place()</code> method. This, in turn, calls the <code>place()</code> method on all the contained <code>Order</code> objects.</p><hr
/><h2>The State Pattern</h2><blockquote
class="pullquote"><p>Gateways only retrieve and persist raw data.</p></blockquote><p>A finite state machine (FSM) is a model that has a finite number of discreet states. Implementing a FSM can be difficult, and the easiest way to do so involves the trusty <code>switch</code> statement. Each <code>case</code> statement represents a current state in the machine, and it knows how to activate the next state.</p><p>But we all know that <code>switch...case</code> statements are less desirable because they produce an unwanted high fan-out on our objects. So forget the <code>switch...case</code> statement, and instead consider the state pattern. The state pattern is composed of several objects: an object to coordinate things, an interface representing an abstract state, and then several implementations &#8211; one for each state. Each state knows which state comes after it, and the state can notify the coordinating object to set its new state to the next in line.</p><div
class="tip-shortcode"><p><strong>When:</strong> FSM-like logic is required to be implemented.</p><p><strong>Why:</strong> To eliminate the problems of a <code>switch...case</code> statement, and to better encapsulate the meaning of each individual state.</p></div><p>A food dispenser could have a <code>main</code> class that has a reference to a <code>state</code> class. Possible state classes might be something like: <code>WaitingForCoin</code>, <code>InsertedCoin</code>, <code>SelectedProduct</code>, <code>WaitingForConfirmation</code>, <code>DeliveringProduct</code>, <code>ReturningChange</code>. Each state performs its job and creates the next state object to send to the coordinator class.</p><hr
/><h2>Decorate with the Decorator Pattern</h2><p>There are times when you deploy classes or modules throughout an application, and you can&#8217;t modify them without radically affecting the system. But, at the same time, you need to add new functionality that your users require.</p><p>The decorator pattern can aid in these situations. It is very simple: take existing functionality and add to it. This is accomplished by extending the original class and providing new functionality at run-time. Old clients continue to use the new object as they would an old one, and new clients will use both the old and new functionality.</p><div
class="tip-shortcode"><p><strong>When:</strong> You can&#8217;t change old classes, but you have to implement new behavior or state.</p><p><strong>Why:</strong> It offers an unintrusive way of adding new functionality.</p></div><p>A simple example is printing data. You print some information to the user as plain text, but you also want to provide the ability to print in HTML. The decorator pattern is one such solution that lets you keep both functionality.</p><h3>Or, Accept a Visitor</h3><p>If your problem of extending functionality is different &#8211; say, you have a complex tree-like structure of objects, and you want to add functionality to many nodes at once &#8211; a simple iteration is not possible, but a visitor might be a viable solution. The downside, however, is that a visitor pattern implementation requires modification to the old class if it wasn&#8217;t designed to accept a visitor.</p><div
class="tip-shortcode"><p><strong>When:</strong> A decorator is not appropriate and some extra complexity is acceptable.</p><p><strong>Why:</strong> To allow and organized approach to defining functionality for several objects but at the price of higher complexity.</p></div><hr
/><h2>Conclusion</h2><blockquote
class="pullquote"><p>Use design patterns to solve your problems, but only if they fit.</p></blockquote><p>Design patterns help solve problems. As an implementation recommendation, never name your classes after the patterns. Instead, find the right names for the right abstractions. This helps you to better discern when you really need a pattern as opposed to just implementing one because you can.</p><p>Some may say that if you don&#8217;t name your class with the pattern&#8217;s name in it, then other developers will have a difficult time understanding your code. If it&#8217;s hard to recognize a pattern, then the problem is in the pattern&#8217;s implementation.</p><p>Use design patterns to solve your problems, but only if they fit. Do not abuse them. You&#8217;ll find that a more simple solution befits a little problem; whereas, you&#8217;ll discover that you need a pattern only after you implement a few other solutions.</p><p>If you&#8217;re new to design patterns, I hope that this article has given you some idea as to how patterns can be helpful in your applications. Thanks for reading!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/0/da"><img src="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/1/da"><img src="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=QErzWmd5JXI:WcrpZmPDoJk:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=QErzWmd5JXI:WcrpZmPDoJk:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=QErzWmd5JXI:WcrpZmPDoJk:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/QErzWmd5JXI" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:86:"http://net.tutsplus.com/tutorials/php/the-whens-and-whys-for-php-design-patterns/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"33";}s:10:"feedburner";a:1:{s:8:"origlink";s:81:"http://net.tutsplus.com/tutorials/php/the-whens-and-whys-for-php-design-patterns/";}s:7:"summary";s:25462:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27862&c=1475446250' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27862&c=1475446250' border='0' alt='' /></a><p>There are plenty of articles that explain what design patterns are, and how to implement them; the web doesn&#8217;t need yet another one of those articles! Instead, in this article, we will more discuss the <i>when</i> and <i>why</i>, rather than the <i>which</i> and <i>how</i>.</p><p>I&#8217;ll present different situations and use-cases for patterns, and will also provide short definitions to help those of you who are not so familiar with these specific patterns. Let&#8217;s get started.</p><p><span
id="more-27862"></span></p><p>This article covers some of the various <i>Agile Design Patterns</i>, documented in Robert C. Martin&#8217;s books. These patterns are modern adaptations of the original design patterns defined and documented by <i><a
href="http://en.wikipedia.org/wiki/Design_Patterns" title="GoF: Design Patterns" target="_blank">The Gang of Four</a></i> in 1994. Martin&#8217;s patterns present a much more recent take on the GoF&#8217;s patterns, and they work better with modern programming techniques and problems. In fact, about 15% of the original patterns were replaced with newer patterns, and the remaining patterns were slightly modernized.</p><hr
/><h2>Let&#8217;s Start by Creating Some Objects</h2><h3>Use a Factory Pattern</h3><p>The factory pattern was invented to help programmers organize the information related to object creation. Objects sometimes have lot of constructor parameters; other times, they must be populated with default information immediately after their creation. These objects should be created in factories, keeping all the information regarding their creation and initialization contained within a single place.</p><div
class="tip-shortcode"><p><strong>When</strong> Use a Factory Pattern when you find yourself writing code to gather information necessary to create objects.</p><p><strong>Why:</strong> Factories help to contain the logic of object creation in a single place. They can also break dependencies to facilitate loose coupling and dependency injection to allow for better testing.</p></div><hr
/><h2>Finding the Data We Need</h2><p>There are two frequently used patterns to retrieve information from a persistence layer or external data source.</p><h3>The Gateway Pattern</h3><p>This pattern defines a communication channel between a persistence solution and the business logic. For simpler applications, it can retrieve or recreate whole objects by itself, but object creation is the responsibility of factories in most complex applications. Gateways simply retrieve and persist raw data.</p><div
class="tip-shortcode"><p><strong>When:</strong> When you need to retrieve or persist information.</p><p><strong>Why:</strong> It offers a simple public interface for complicated persistence operations. It also encapsulates persistence knowledge and decouples business logic from persistence logic.</p></div><p>In fact, the gateway pattern is just a particular implementation of another design pattern that we&#8217;ll discuss shortly: the adapter pattern.</p><h3>Go with the Proxy</h3><p>There are times when you can not (or do not want to) expose the knowledge of the persistence layer to your business classes. The proxy pattern is a good way to fool your business classes into thinking they are using already existing objects.</p><div
class="tip-shortcode"><p><strong>When:</strong> You have to retrieve information from a persistence layer or external source, but don&#8217;t want your business logic to know this.</p><p><strong>Why:</strong> To offer a non-intrusive approach to creating objects behind the scenes. It also opens the possibility to retrieve these object on the fly, lazily, and from different sources.</p></div><p>A proxy effectively implements the same interface as a real object and mimics its functionality. The business logic simply uses it as if it were a real object, but in fact, the proxy creates the object if one doesn&#8217;t exist.</p><blockquote
class="pullquote"><p>The active object pattern also played a part in early multi-tasking systems.</p></blockquote><p>Okay, okay. That great and all, but how can we find the objects that we need to create?</p><h3>Ask a Repository</h3><p>The repository pattern is very useful for implementing search methods and mini-query languages. It takes these queries and uses a gateway to obtain the data for a factory to produce the objects you need.</p><p>The repository pattern is different from the other patterns; it exists as part of Domain Driven Design (DDD), and is not included as part of Robert C. Martin&#8217;s book.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to create multiple objects based on search criteria, or when you need to save multiple objects to the persistence layer.</p><p><strong>Why:</strong> To let clients that need specific objects to work with a common and well isolated query and persistence language. It removes even more creation-related code from the business logic.</p></div><p>But what if the repository cannot find the objects? One option would be to return a <code>NULL</code> value, but doing so has two side effects:</p><ul><li>It throws a <i>refused bequest</i> if you try to call a method on such an object.</li><li>It forces you to include numerous null checks (<code>if(is_null($param)) return;</code>) in your code.</li></ul><p>A better approach is to return a <code>null</code> object.</p><h3>The Null Object Pattern</h3><p>A null object implements the same interface of your other objects, but the object&#8217;s members return a neutral value. For example, a method that returns a string would return an empty string; another member returning a numeric value would return zero. This forces you to implement methods that do not return meaningful data, but you can use these objects without worrying about refused bequest or littering your code with null checks.</p><div
class="tip-shortcode"><p><strong>When:</strong> You frequently check for <code>null</code> or you have refused bequests.</p><p><strong>Why:</strong> It can add clarity to your code and forces you to think more about the behavior of your objects.</p></div><p>It&#8217;s not unusual to call many methods on an object before it can do its job. There are situations when you must prepare an object after its creation before you can truly use it. This leads to code duplication when creating those objects in different places.</p><h3>You Need the Command Pattern</h3><div
class="tip-shortcode"><p><strong>When:</strong> When you have to perform many operations to prepare objects for use.</p><p><strong>Why:</strong> To move complexity from the consuming code to the creating code.</p></div><p>This sounds good, doesn&#8217;t it? In fact, it is quite useful in many situations. The command pattern is widely used for implementing transactions. If you add a simple <code>undo()</code> method to a command object, it can track all the undo transactions it performed and reverse them if necessary.</p><p>So now you have ten (or more) command objects, and you want them running concurrently. You can gather them into an active object.</p><h3>The Active Object</h3><p>The simple and interesting active object has only one responsibility: keep a list of command objects and run them.</p><div
class="tip-shortcode"><p><strong>When:</strong> Several similar objects have to execute with a single command.</p><p><strong>Why:</strong> It forces clients to perform a single task and affect multiple objects.</p></div><p>An active object removes each command from its list after the command&#8217;s execution; meaning, you can execute the command only once. Some real world examples of an active object are:</p><blockquote
class="pullquote"><p>Design patterns are here to solve problems.</p></blockquote><ul><li><strong>Shopping Cart</strong> &#8211; Executing a <code>buy()</code> command on each product removes them from the cart.</li><li><strong>Financial Transactions</strong> &#8211; Grouping transactions into a single list and executing them with a simple call to the list manager&#8217;s active object would remove the transactions from the queue.</li></ul><p>The active object pattern also played a part in early multi-tasking systems. Each object inside an active object would keep a reference to the active object. They would execute a portion of their jobs and then put themselves back into the queue. Even in today&#8217;s systems, you can use an active object to let other objects work while you wait for a response from another application.</p><hr
/><h2>Reusability</h2><p>I am positive that you&#8217;ve heard the big promise of object oriented programming: code reuse. Early adopters of OOP envisioned using universal libraries and classes in millions of different projects. Well, it never happened.</p><h3>Make Some Template Methods Instead</h3><p>This pattern allows for the partial reuse of code. It&#8217;s practical with multiple algorithms which only slightly differ from one another.</p><div
class="tip-shortcode"><p><strong>When:</strong> Eliminate duplication in a simple way.</p><p><strong>Why:</strong> There is duplication and flexibility is not a problem.</p></div><p>But flexibility is nice. What if I really need it?</p><h3>It&#8217;s Time For a Strategy</h3><div
class="tip-shortcode"><p><strong>When:</strong> Flexibility and reusability is more important than simplicity.</p><p><strong>Why:</strong> Use it to implement big, interchangeable chunks of complicated logic, while keeping a common algorithm signature.</p></div><p>For example, you can create a generic <code>Calculator</code> and then use different <code>ComputationStrategy</code> objects to perform the calculations. This is a moderately used pattern, and it is most powerful when you have to define many conditional behaviors.</p><hr
/><h2>Discover-ability</h2><p>As projects grow, it becomes increasingly difficult for external users to access our application. That&#8217;s one reason to offer a well-defined entry point to the application or module in question. Other such reasons may include the desire to conceal the module&#8217;s internal workings and structure.</p><h3>Present a Facade</h3><p>A facade is essentially an API &#8211; a nice and client-facing interface. When a client calls one of these nice methods, the facade delegates a series of calls to the classes it hides in order to provide the client with the required information or desired result.</p><div
class="tip-shortcode"><p><strong>When:</strong> To simplify your API or intentionally conceal inner business logic.</p><p><strong>Why:</strong> You can control the API and the real implementations and logic independently.</p></div><p>Control is good, and many times you need to perform a task when something changes. Users have to be notified, red LEDs have to blink, an alarm has to sound&#8230; you get the idea.</p><blockquote><p> The popular <a
href="http://laravel.com">Laravel</a> framework makes excellent use of the Facade Pattern.</p></blockquote><h3>Subscribe to an Observer</h3><blockquote
class="pullquote"><p>A null object implements the same interface as your other objects.</p></blockquote><p>The observer pattern offers an easy way to monitor objects and take actions when conditions change. There are two types of observer implementations:</p><ul><li><strong>Polling</strong> &#8211; Objects accept subscribers. Subscribers observe the object and are notified on specific events. Subscribers <i>ask</i> the observed objects for more information in order to take an action.</li><li><strong>Push</strong> &#8211; Like the polling method, objects accept subscribers, and subscribers are notified when an event occurs. But when a notification happens, <i>the observer also receives a hint</i> that the observer can act on.</li></ul><div
class="tip-shortcode"><p><strong>When:</strong> To provide a notification system inside your business logic or to the outside world.</p><p><strong>Why:</strong> The pattern offers a way to communicate events to any number of different objects.</p></div><p>Use cases for this pattern are email notifications, logging daemons, or messaging systems. Of course, in real life, there are countless other ways to use it.</p><h3>Coordinate The Effects</h3><p>The observer pattern can be extended with a mediator pattern. This pattern takes two objects as parameters. The mediator subscribes itself to the first parameter, and when a change happens to the observed object, the mediator decides what to do on the second object.</p><div
class="tip-shortcode"><p><strong>When:</strong> The affected objects can not know about the observed objects.</p><p><strong>Why:</strong> To offer a hidden mechanism of affecting other objects in the system when one object changes.</p></div><hr
/><h2>Singularity</h2><p>Sometimes, you need special objects that are unique in your application, and you want to ensure that all consumers can see any change made to these objects. You also want to prevent creating multiple instances of such objects for certain reasons, like long initialization time or problems with concurrent actions to some third party libraries.</p><h3>Use a Singleton</h3><p>A singleton is an object having a private constructor and a public <code>getInstance()</code> method. This method ensures that only one instance of the object exists.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to achieve singularity and want a cross platform, lazily evaluated solution which also offers the possibility of creation through derivation.</p><p><strong>Why:</strong> To offer a single point of access when needed.</p></div><h3>Or Write a Monostate Object</h3><p>Another approach to singularity is the monostate design pattern. This solution uses a trick offered by object oriented programming languages. It has dynamic public methods which get or set the values of static private variables. This, in turn, ensures that all instances of such classes share the same values.</p><div
class="tip-shortcode"><p><strong>When:</strong> Transparency, derivabitility, and polymorphism are preferred together with singularity.</p><p><strong>Why:</strong> To hide from the users/clients the fact that the object offers singularity.</p></div><p>Pay special attention to singularity. It pollutes the global namespace and, in most cases, can be replaced with something better suited for that particular situation.</p><hr
/><h2>Controlling Different Objects</h2><blockquote
class="pullquote"><p>The repository pattern is quite useful for implementing search methods&#8230;</p></blockquote><p>So you have a switch and a light. The switch can turn the light on and off, but, now, you&#8217;ve purchased a fan and want to use your old switch with it. That&#8217;s easy to accomplish in the physical world; take the switch, connect the wires, and viola.</p><p>Unfortunately, it&#8217;s not so easy in the programming world. You have a <code>Switch</code> class and a <code>Light</code> class. If your <code>Switch</code> uses the <code>Light</code>, how could it use the <code>Fan</code>?</p><p>Easy! Copy and paste the <code>Switch</code>, and change it to use the <code>Fan</code>. But that&#8217;s code duplication; it&#8217;s the equivalent of buying another switch for the fan. You could extend <code>Switch</code> to <code>FanSwitch</code>, and use that object instead. But what if you want to use a <code>Button</code> or <code>RemoteControl</code>, instead of a <code>Switch</code>?</p><h3>The Abstract Server Pattern</h3><p>This is the simplest pattern ever invented. It only uses an interface. That&#8217;s it, but there are several different implementations.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to connect objects and maintain flexibility.</p><p><strong>Why:</strong> Because it is the simplest way to achieve flexibility, while respecting both the dependency inversion principle and the open close principle.</p></div><p>PHP is dynamically typed. This means that you can omit interfaces and use different objects in the same context &#8211; risking a refused bequest. However, PHP also allows for the definition of interfaces, and I recommend you use this great functionality to provide clarity to the intent of your source code.</p><p>But you already have a bunch of classes you want to talk to? Yes, of course. There are many libraries, third-party APIs, and other modules that one has to talk to, but this does not mean that our business logic has to know the details of such things.</p><h3>Plug in an Adapter</h3><p>The adapter pattern simply creates a correspondence between the business logic and something else. We have already seen such a pattern in action: the gateway pattern.</p><div
class="tip-shortcode"><p><strong>When:</strong> You need to create a connection with a pre-existing and potentially changing module, library, or API.</p><p><strong>Why:</strong> To allow your business logic to rely only on the public methods the adapter offers, and permit changing the other side of the adapter easily.</p></div><p>If either of the above patterns don&#8217;t fit with your situation, then you could use&#8230;</p><h3>The Bridge Pattern</h3><p>This is a very complicated pattern. I personally do not like it because it is usually easier to take a different approach. But for those special cases, when other solutions fail, you can consider the bridge pattern.</p><div
class="tip-shortcode"><p><strong>When:</strong> The adapter pattern is not enough, and you change classes on both sides of the pipe.</p><p><strong>Why:</strong> To offer increased flexibility at the cost of significant complexity.</p></div><hr
/><h2>The Composite Pattern</h2><p>Consider that you have a script with similar commands, and you want make a single call to run them. Wait! Didn&#8217;t we already see something like this earlier? The active object pattern?</p><p>Yes, yes we did. But this one is a bit different. It&#8217;s the composite pattern, and like the active object pattern, it keeps a list of objects. But calling a method on a composite object calls the same method on all of its objects without removing them from the list. The clients calling a method are thinking they are talking to a single object of that particular type, but in fact, their actions are applied to many, many objects of the same type.</p><div
class="tip-shortcode"><p><strong>When:</strong> You have to apply an action to several similar objects.</p><p><strong>Why:</strong> To reduce duplication and simplify how similar objects are called.</p></div><p>Here&#8217;s an example: you have an application that is capable of creating and placing <code>Orders</code>. Assume you have three orders: <code>$order1</code>, <code>$order2</code> and <code>$order3</code>. You could call <code>place()</code> on each of them, or you could contain those orders in a <code>$compositeOrder</code> object, and call its <code>place()</code> method. This, in turn, calls the <code>place()</code> method on all the contained <code>Order</code> objects.</p><hr
/><h2>The State Pattern</h2><blockquote
class="pullquote"><p>Gateways only retrieve and persist raw data.</p></blockquote><p>A finite state machine (FSM) is a model that has a finite number of discreet states. Implementing a FSM can be difficult, and the easiest way to do so involves the trusty <code>switch</code> statement. Each <code>case</code> statement represents a current state in the machine, and it knows how to activate the next state.</p><p>But we all know that <code>switch...case</code> statements are less desirable because they produce an unwanted high fan-out on our objects. So forget the <code>switch...case</code> statement, and instead consider the state pattern. The state pattern is composed of several objects: an object to coordinate things, an interface representing an abstract state, and then several implementations &#8211; one for each state. Each state knows which state comes after it, and the state can notify the coordinating object to set its new state to the next in line.</p><div
class="tip-shortcode"><p><strong>When:</strong> FSM-like logic is required to be implemented.</p><p><strong>Why:</strong> To eliminate the problems of a <code>switch...case</code> statement, and to better encapsulate the meaning of each individual state.</p></div><p>A food dispenser could have a <code>main</code> class that has a reference to a <code>state</code> class. Possible state classes might be something like: <code>WaitingForCoin</code>, <code>InsertedCoin</code>, <code>SelectedProduct</code>, <code>WaitingForConfirmation</code>, <code>DeliveringProduct</code>, <code>ReturningChange</code>. Each state performs its job and creates the next state object to send to the coordinator class.</p><hr
/><h2>Decorate with the Decorator Pattern</h2><p>There are times when you deploy classes or modules throughout an application, and you can&#8217;t modify them without radically affecting the system. But, at the same time, you need to add new functionality that your users require.</p><p>The decorator pattern can aid in these situations. It is very simple: take existing functionality and add to it. This is accomplished by extending the original class and providing new functionality at run-time. Old clients continue to use the new object as they would an old one, and new clients will use both the old and new functionality.</p><div
class="tip-shortcode"><p><strong>When:</strong> You can&#8217;t change old classes, but you have to implement new behavior or state.</p><p><strong>Why:</strong> It offers an unintrusive way of adding new functionality.</p></div><p>A simple example is printing data. You print some information to the user as plain text, but you also want to provide the ability to print in HTML. The decorator pattern is one such solution that lets you keep both functionality.</p><h3>Or, Accept a Visitor</h3><p>If your problem of extending functionality is different &#8211; say, you have a complex tree-like structure of objects, and you want to add functionality to many nodes at once &#8211; a simple iteration is not possible, but a visitor might be a viable solution. The downside, however, is that a visitor pattern implementation requires modification to the old class if it wasn&#8217;t designed to accept a visitor.</p><div
class="tip-shortcode"><p><strong>When:</strong> A decorator is not appropriate and some extra complexity is acceptable.</p><p><strong>Why:</strong> To allow and organized approach to defining functionality for several objects but at the price of higher complexity.</p></div><hr
/><h2>Conclusion</h2><blockquote
class="pullquote"><p>Use design patterns to solve your problems, but only if they fit.</p></blockquote><p>Design patterns help solve problems. As an implementation recommendation, never name your classes after the patterns. Instead, find the right names for the right abstractions. This helps you to better discern when you really need a pattern as opposed to just implementing one because you can.</p><p>Some may say that if you don&#8217;t name your class with the pattern&#8217;s name in it, then other developers will have a difficult time understanding your code. If it&#8217;s hard to recognize a pattern, then the problem is in the pattern&#8217;s implementation.</p><p>Use design patterns to solve your problems, but only if they fit. Do not abuse them. You&#8217;ll find that a more simple solution befits a little problem; whereas, you&#8217;ll discover that you need a pattern only after you implement a few other solutions.</p><p>If you&#8217;re new to design patterns, I hope that this article has given you some idea as to how patterns can be helpful in your applications. Thanks for reading!</p>
<p><a href="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/0/da"><img src="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/1/da"><img src="http://feedads.g.doubleclick.net/~a/wvfkdX-7tUmlT6m54nk9PfWYAGc/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=QErzWmd5JXI:WcrpZmPDoJk:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=QErzWmd5JXI:WcrpZmPDoJk:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=QErzWmd5JXI:WcrpZmPDoJk:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=QErzWmd5JXI:WcrpZmPDoJk:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/QErzWmd5JXI" height="1" width="1"/>";s:14:"date_timestamp";i:1352126933;}i:8;a:13:{s:5:"title";s:38:"Better CoffeeScript Testing With Mocha";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/bLERbf6u_sM/";s:8:"comments";s:98:"http://net.tutsplus.com/tutorials/javascript-ajax/better-coffeescript-testing-with-mocha/#comments";s:7:"pubdate";s:31:"Thu, 01 Nov 2012 13:54:47 +0000";s:2:"dc";a:1:{s:7:"creator";s:14:"Andrew Burgess";}s:8:"category";s:29:"JavaScript & AJAXcoffeescript";s:4:"guid";s:32:"http://net.tutsplus.com/?p=24696";s:11:"description";s:23275:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=24696&c=2048186860' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=24696&c=2048186860' border='0' alt='' /></a><p>Recently, I&#8217;ve been doing a considerable amount of <a
href="http://coffeescript.org">CoffeeScript</a> work. One problem I ran into early-on was testing: I didn&#8217;t want to manually convert my CoffeeScript to JavaScript before I could test it. Instead, I wanted to test from CoffeeScript directly. How&#8217;d I end up doing it? Read on to find out!</p><p><span
id="more-24696"></span></p> November of 2012<hr
/><blockquote
class=pullquote><p>You&#8217;ll need to have <a
href="http://nodejs.org/">Node.js</a> and <a
href="http://npmjs.org/">Node Package Manager</a> installed.</p></blockquote><p>Before we continue on, I&#8217;ll point out that you need to have a decent knowledge of <a
href="http://coffeescript.org/">CoffeeScript</a> for this tutorial; I won&#8217;t be explaining the bits and pieces here. If you&#8217;re interested in CoffeeScript, you should check out the <a
href='http://net.tutsplus.com/tag/coffeescript/'>CoffeeScript tuts available here on Nettuts+</a>, or the <a
href='http://coffeescript.org/'>CoffeeScript documentation</a>.</p><p>Additionally, you&#8217;ll need to have Node.js and the Node Package Manager (npm) installed for this tutorial. If you don&#8217;t have &#8216;em installed, no worries: head over to <a
href='http://nodejs.org/'>nodejs.org</a> and download the installer for your platform; then, well, install it!</p><hr
/><h2>Meeting Mocha and Chai</h2><p>We&#8217;ll be building the beginnings of a todo list application (clich&eacute;, I know). These will be CoffeeScript classes. Then, we&#8217;ll write some tests with <a
href="http://visionmedia.github.com/mocha/">Mocha</a> and Chai to test that functionality.</p><p>Why both Mocha and Chai? Well, Mocha is a testing framework, but it doesn&#8217;t include the actual assertions component. That might sound strange: after all, there isn&#8217;t much more to a testing library, is there? Well, there is, in Mocha&#8217;s case. The features that brought me to the library are two-fold: the ability to run tests from the command line (instead of having an HTML page to run them in the browser), and the ability to run test in CoffeeScripts, without having to convert that code to JavaScript (as least manually: Mocha does it behind the scenes). There are other features, too, that I won&#8217;t be talking about here, including:</p><ul><li>You can easily test asynchronous code.</li><li>You can watch for especially slow tests.</li><li>You can output the results in a number of different formats.</li></ul><p>And on, and on. See more <a
href='http://visionmedia.github.com/mocha/'>at the Mocha home page</a>. To install Mocha simply run <code>npm install -g mocha</code>, and you&#8217;re set.</p><p>As for Chai: it&#8217;s a great assertion library that offers interfaces for doing both <a
href='https://en.wikipedia.org/wiki/Behavior_Driven_Development'>BDD</a> and <a
href='https://en.wikipedia.org/wiki/Test-driven_development'>TDD</a>; you can use it both in the browser or on the command line via node, which is how we&#8217;ll use it today. Install it for Node, via <code>npm install -g chai</code>.</p><p>Now that we have our libraries installed, let&#8217;s start writing some code.</p><hr
/><h2>Setting Up Our Project</h2><p>Let&#8217;s begin by setting up a mini project. Create a project folder. Then, create two more folders in that one: <code>src</code>, and <code>test</code>. Our CoffeeScript code will go in the <code>src</code> folder, and our tests will go in, you guessed it, the <code>tests</code> folder. Mocha looks for a <code>test</code> folder by default, so by doing this, we&#8217;ll save ourselves some typing later.</p><blockquote
class=pullquote><p>Mocha looks for a <code>test</code> folder by default.</p></blockquote><p>We&#8217;re going to create two CoffeeScript classes: <code>Task</code>, which will be a todo item, and <code>TaskList</code>, which will be a list of todo items (yes, it&#8217;s more than an array). We&#8217;ll put them both in the <code>src/task.coffee</code> file. Then, the tests for this will be in <code>test/taskTest.coffee</code>. Of course, we could split &#8216;em into their own files, but we&#8217;re just not going to do that today.</p><p>We have to start by importing the Chai library and enabling the BDD syntax. Here&#8217;s how:</p><pre class="js" name="code">chai = require &#39;chai&#39;
chai.should()</pre><p>By calling the <code>chai.should</code> method, we&#8217;re actually adding a <code>should</code> property to <code>Object.prototype</code>. This allows us to write tests that read like this:</p><pre class="js" name="code">task.name.should.equal &quot;some string&quot;</pre><p>If you prefer the TDD syntax, you can do this:</p><pre class="js" name="code">expect = chai.expect</pre><p>&#8230; which allows you to write tests like this:</p><pre class="js" name="code">expect(task.name).to.equal &quot;some string&quot;</pre><p>We&#8217;ll actually have to use both of these, as you&#8217;ll see; however, we&#8217;ll use the BDD syntax as much as possible.</p><p>Now we&#8217;ll need to import our <code>Task</code> and <code>TaskList</code> classes:</p><pre class="js" name="code">{TaskList, List} = require &#39;../src/task&#39;</pre><p>If you aren&#8217;t familiar with this syntax, that&#8217;s CoffeeScript&#8217;s destructured assignment at work, as well as some of its object literal sugar. Basically, our <code>require</code> call returns an object with two properties, which are our classes. This line pulls them out of that object and gives us two variables named <code>Task</code> and <code>TaskList</code>, each of which points to the respective class.</p><hr
/><h2>Writing Our First Tests</h2><p>Great! Now, how about a test? The beauty of the Mocha syntax is that its blocks (<code>describe</code> and <code>it</code>) are identical to <a
href='http://pivotal.github.com/jasmine/'>Jasmine&#8217;s</a> (both being very similar to RSpec). Here&#8217;s our first test:</p><pre class="js" name="code">describe &#39;Task instance&#39;, -&gt;
	task1 = task2 = null
	it &#39;should have a name&#39;, -&gt;
		task1 = new Task &#39;feed the cat&#39;
		task1.name.should.equal &#39;feed the cat&#39;</pre><p>We start with a <code>describe</code> call: all these tests are for a Test instance. By setting <code>test1 = test2 = null</code> outside our individual tests, we can use those values for multiple tests.</p><p>Then, in our first test, we&#8217;re simply creating a task and checking to see that its name property has the correct value. Before writing the code for this, let&#8217;s add two more tests:</p><pre class="js" name="code">it &#39;should be initially incomplete&#39;, -&gt;
	task1.status.should.equal &#39;incomplete&#39;
it &#39;should be able to be completed&#39;, -&gt;
	task1.complete().should.be.true
	task1.status.should.equal &#39;complete&#39;</pre><p>Ok, let&#8217;s run these tests to make sure they&#8217;re failing. To do this, let&#8217;s open a command prompt and <code>cd</code> to your project folder. Then, run this command:</p><pre class="js" name="code">mocha --compilers coffee:coffee-script</pre><p>Mocha doesn&#8217;t check for CoffeeScript by default, so we have to use the <code>--compilers</code> flag to tell Mocha what compiler to use if it finds a file with the <code>coffee</code> file extension. You should get errors that look like this:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/errors.png' /></div><p>If, instead of seeing that, you get the error <code>Cannot find module &#39;../src/task&#39;</code>, it&#8217;s because your <code>src/task.coffee</code> file doesn&#8217;t exist yet. Make said file, and you should get said error.</p><hr
/><h2>Coding Our First Features</h2><p>Well, now that we have failing tests, it&#8217;s time to write the code, correct? Open that <code>src/task.coffee</code> file and let&#8217;s get cracking.</p><pre class="js" name="code">class Task
	constructor: (@name) -&gt;</pre><p>Just this is enough to get our first test passing. If you aren&#8217;t familiar with that parameter syntax, that just sets whatever value was passed to <code>new Task</code> to the <code>@name</code> (or <code>this.name</code>) property. However, let&#8217;s add another line to that constructor:</p><pre class="js" name="code">@status = &#39;incomplete&#39;</pre><p>That&#8217;s good. Now, head back to the terminal and re-run our tests. You&#8217;ll find that&mdash;wait a second, nothing&#8217;s changed! Why aren&#8217;t our first two tests passing?</p><p>A simple problem, actually. Because the CoffeeScript compiler wraps the code in each file in a <a
href='http://benalman.com/news/2010/11/immediately-invoked-function-expression/'>IIFE</a> (or, a self-invoking anonymous function), we need to &#8220;export&#8221; anything we want to be accessible from other files. In the browser, you&#8217;d do something like <code>window.Whatever = Whatever</code>. For Node, you can use either <code>global</code> or <code>exports</code>. We&#8217;ll be using <code>exports</code>, since 1) that&#8217;s considered best practice, and 2) that&#8217;s what we prepared for when setting up our tests (remember our <code>require</code> call?). Therefore, at the end of our <code>task.coffee</code> file, add this:</p><pre class="js" name="code">root = exports ? window
root.Task = Task</pre><p>With that in place, you should find that two of our three tests are now passing:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/two_passing.png' /></div><p>To get the last test to pass, we&#8217;ll have to add a <code>complete</code> method. Try this:</p><pre class="js" name="code">complete: -&gt;
	@status = &#39;complete&#39;
	true</pre><p>Now, all tests pass:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/all_passing.png' /></div><p>Now&#8217;s a good time to mention that Mocha has a number of different reports: these are just different ways to output the test results. You can run <code>mocha --reporters</code> to see your options:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/reporters.png' /></div><p>By default, Mocha uses the dot reporter. However, I prefer the spec reporter, so I tack <code>-R spec</code> on the end of command (<code>-R</code> is the reporter-setting flag).</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/spec_reporter.png' /></div><hr
/><h2>Adding a Feature</h2><p>Let&#8217;s add a feature to our <code>Task</code> class: we&#8217;ll let tasks be dependent on other tasks. If the &#8220;parent&#8221; task isn&#8217;t completed, the &#8220;child&#8221; task can&#8217;t be done. We&#8217;ll keep this feature simple and allow tasks to have only one sub-task. We also won&#8217;t check for recursiveness, so while it will be possible to set two tasks to be the parent and child of each other, it will render both tasks incomplete-able.</p><p>Tests first!</p><pre class="js" name="code">it &#39;should be able to be dependent on another task&#39;, -&gt;
	task1 = new Task &#39;wash dishes&#39;
	task2 = new Task &#39;dry dishes&#39;
	task2.dependsOn task1
	task2.status.should.equal &#39;dependent&#39;
	task2.parent.should.equal task1
	task1.child.should.equal task2
it &#39;should refuse completion it is dependent on an uncompleted task&#39;, -&gt;
	(-&gt; task2.complete()).should.throw &quot;Dependent task &#39;wash dishes&#39; is not completed.&quot;</pre><p><code>Task</code> instances are going to have a <code>dependsOn</code> method, which tasks the task that will become their parent. Tasks that have a parent task should have a status of &#8220;dependent.&#8221; Also, both tasks get either a <code>parent</code> or <code>child</code> property that points to the appropriate task instance.</p><p>In the second test there, we say that a task with an incomplete parent task should throw an error when its <code>complete</code> method is called. Notice how test syntax works: we need to call <code>should</code> off of a function, and not the result of the function: therefore, we wrap the function in parentheses. This way, the test library can call the function itself and check for the error.</p><p>Run those tests and you&#8217;ll see that both fail. Coding time!</p><pre class="js" name="code">dependsOn: (@parent) -&gt;
	@parent.child = @
	@status = &#39;dependent&#39;</pre><p>Again, very simple: we just set the task parameter to the parent task, and give it a child property which points to <code>this</code> task instance. Then, we set the status of <code>this</code> task to be &#8220;dependent.&#8221;</p><p>If you run this now, you&#8217;ll see that one of our tests is passing, but the second isn&#8217;t: that&#8217;s because our <code>complete</code> method doesn&#8217;t check for an uncompleted parent task. Let&#8217;s change that.</p><pre class="js" name="code">complete: -&gt;
	if @parent? and @parent.status isnt &#39;completed&#39;
		throw &quot;Dependent task &#39;#{@parent.name}&#39; is not completed.&quot;
	@status = &#39;complete&#39;
	true</pre><p>Here&#8217;s the completed <code>complete</code> method: if there&#8217;s a parent task, and it isn&#8217;t completed, we throw an error. Otherwise, we complete the task. Now, all tests should pass.</p><hr
/><h2>Building the TaskList</h2><p>Next, we&#8217;ll build the <code>TaskList</code> class. Again, we&#8217;ll start with a test:</p><pre class="js" name="code">describe &#39;TaskList&#39;, -&gt;
    taskList = null
    it &#39;should start with no tasks&#39;, -&gt;
        taskList = new TaskList
        taskList.tasks.length.should.equal 0
        taskList.length.should.equal 0</pre><p>This is old-hat to you by now: we&#8217;re creating a <code>TaskList</code> object and checking its <code>tasks</code> and <code>length</code> properties to makes sure their both at zero. As you might guess, <code>tasks</code> is an array that holds the tasks, while <code>length</code> is just a handy property that we&#8217;ll update when adding or removing tasks; it just saves us from having to write <code>list.tasks.length</code>.</p><p>To make this test pass, we&#8217;ll make this constructor:</p><pre class="js" name="code">class TaskList
	constructor: () -&gt;
		@tasks = []
		@length = 0</pre><p>Good start, and that gets our test passing.</p><p>We&#8217;ll want to be able to add tasks to a task list, right? We&#8217;ll have an <code>add</code> method that can take either a <code>Task</code> instance, or a string which it will convert to a <code>Task</code> instance.</p><p>Our tests:</p><pre class="js" name="code">it &#39;should accept new tasks as tasks&#39;, -&gt;
    task = new Task &#39;buy milk&#39;
    taskList.add task
    taskList.tasks[0].name.should.equal &#39;buy milk&#39;
    taskList.length.should.equal 1
it &#39;should accept new tasks as string&#39;, -&gt;
    taskList.add &#39;take out garbage&#39;
    taskList.tasks[1].name.should.equal &#39;take out garbage&#39;
    taskList.length.should.equal 2</pre><p>First, we add an actual <code>Task</code> object, and check the <code>taskList.tasks</code> array to verify that it&#8217;s been added. Then, we add a string, and make sure that a <code>Task</code> object with the right name was added to the <code>tasks</code> array. In both cases, we check the length of <code>taskList</code> as well, to make sure that it&#8217;s being property updated.</p><p>And the function:</p><pre class="js" name="code">add: (task) -&gt;
    if typeof task is &#39;string&#39;
        @tasks.push new Task task
    else
        @tasks.push task
    @length = @tasks.length</pre><p>Pretty self-explanatory, I think. And now our tests pass:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/tasklist_tests.png' /></div><p>Of course, we might want to remove tasks from our list, right?</p><pre class="js" name="code">it &#39;should remove tasks&#39;, -&gt;
	i = taskList.length - 1
	taskList.remove taskList.tasks[i]
	expect(taskList.tasks[i]).to.not.be.ok</pre><p>First, we call the <code>remove</code> method (yet to be written, of course), passing it the last task currently in the list. Sure, we could just hardcode the index <code>1</code>, but I&#8217;ve done it this way because that makes this test flexible: if we changed our previous tests or added more tests above this one, that might have to change. Of course, we have to remove the last one because otherwise, the task after it will take its place and there&#8217;ll be something at that index when we&#8217;re expecting there to be nothing.</p><p>And speaking of expecting, notice that we&#8217;re using the <code>expect</code> function and syntax here instead of our usual <code>should</code>. This is because <code>taskList.tasks[i]</code> will be <code>undefined</code>, which doesn&#8217;t inherit from <code>Object.prototype</code>, and therefore we can&#8217;t use <code>should</code>.</p><p>Oh, yeah, we still need to write that <code>remove</code> function:</p><pre class="js" name="code">remove: (task) -&gt;
    i = @tasks.indexOf task
    @tasks = @tasks[0...i].concat @tasks[i+1..] if i &gt; -1
    @length = @tasks.length</pre><p>Some fancy array footwork combined with CoffeeScript&#8217;s ranges and array splicing shorthand closes this deal for us. We&#8217;re simply splitting off all the items before the one to remove and all the items after it; the we <code>concat</code> those two arrays together. Of course, we&#8217;ll update <code>@length</code> accordingly. Can you say &#8220;passing tests&#8221;?</p><p>Let&#8217;s do one more thing. We want to print our a (relatively) nice-looking list of the current tasks. This will be our most complex (or at least, our longest) test yet:</p><pre class="js" name="code">    it &#39;should print out the list&#39;, -&gt;
        taskList = new TaskList
        task0 = new Task &#39;buy milk&#39;
        task1 = new Task &#39;go to store&#39;
        task2 = new Task &#39;another task&#39;
        task3 = new Task &#39;sub-task&#39;
        task4 = new Task &#39;sub-sub-task&#39;
        taskList.add task0
        taskList.add task1
        taskList.add task2
        taskList.add task3
        taskList.add task4
        task0.dependsOn task1
        task4.dependsOn task3
        task3.dependsOn task2
        task1.complete()
        desiredOutput = &quot;&quot;&quot;Tasks
- buy milk (depends on &#39;go to store&#39;)
- go to store (completed)
- another task
- sub-task (depends on &#39;another task&#39;)
- sub-sub-task (depends on &#39;sub-task&#39;)
&quot;&quot;&quot;
		taskList.print().should.equal desiredOutput</pre><p>What&#8217;s going on here? First, we&#8217;re creating a new <code>TaskList</code> object so that we start from scratch. Then, we create five tasks and add them to <code>taskList</code>. Next, we set up a few dependencies. Finally we complete one of our tasks.</p><p>We&#8217;re using CoffeeScript&#8217;s heredoc syntax to create a multi-line string. As you can see, we&#8217;re keeping it pretty simple. If a task has a parent task, it&#8217;s mentioned in parentheses after the task name. If a task is completed, we put that, too.</p><p>Ready to write the function?</p><pre class="js" name="code">print: -&gt;
    str = &quot;Tasks\n\n&quot;
    for task in @tasks
        str += &quot;- #{task.name}&quot;
        str += &quot; (depends on &#39;#{task.parent.name}&#39;)&quot; if task.parent?
        str += &#39; (complete)&#39; if task.status is &#39;complete&#39;
        str += &quot;\n&quot;
    str</pre><p>It&#8217;s actually pretty straightforward: we just look over the <code>@tasks</code> array and add &#8216;em to a string. If they have a parent, we add that, and if they&#8217;re complete, we add that too. Notice that we&#8217;re using the modifier form of the <code>if</code> statement, to tighten up our code. Then, we return the string.</p><p>Now, all our tests should pass:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/all_tests.png' /></div><hr
/><h2>Wrapping Up</h2><blockquote
class=pullquote><p>Try adding a few features to get the hang of it all.</p></blockquote><p>That&#8217;s the extent of our little project today. You can download the code from the top of this page; in fact, why don&#8217;t you try adding a few features to get the hang of it all? Here are a few ideas:</p><ul><li>Prevent <code>Task</code> instances from being able to depend on each other (recursive dependencies).</li><li>Make the <code>TaskList::add</code> method throw an error if it receives something other than a string or a <code>Task</code> object.</li></ul><p>These days, I&#8217;m finding CoffeeScript more and more attractive, but the biggest downside to it is that it must be compiled to JavaScript before it&#8217;s useful. I&#8217;m grateful for anything that negates some of that workflow breaker, and Mocha definitely does that. Of course, it&#8217;s not perfect (since it&#8217;s compiling to JS before running the code, line numbers in errors don&#8217;t match up with your CoffeeScript line numbers), but it&#8217;s a step in the right direction for me!</p><p>How about you? If you&#8217;re using CoffeeScript, how have you been doing testing? Let me know in the comments.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/0/da"><img src="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/1/da"><img src="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=bLERbf6u_sM:YRQGHIZep3Y:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=bLERbf6u_sM:YRQGHIZep3Y:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=bLERbf6u_sM:YRQGHIZep3Y:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/bLERbf6u_sM" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:94:"http://net.tutsplus.com/tutorials/javascript-ajax/better-coffeescript-testing-with-mocha/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"33";}s:10:"feedburner";a:1:{s:8:"origlink";s:89:"http://net.tutsplus.com/tutorials/javascript-ajax/better-coffeescript-testing-with-mocha/";}s:7:"summary";s:23275:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=24696&c=2048186860' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=24696&c=2048186860' border='0' alt='' /></a><p>Recently, I&#8217;ve been doing a considerable amount of <a
href="http://coffeescript.org">CoffeeScript</a> work. One problem I ran into early-on was testing: I didn&#8217;t want to manually convert my CoffeeScript to JavaScript before I could test it. Instead, I wanted to test from CoffeeScript directly. How&#8217;d I end up doing it? Read on to find out!</p><p><span
id="more-24696"></span></p> November of 2012<hr
/><blockquote
class=pullquote><p>You&#8217;ll need to have <a
href="http://nodejs.org/">Node.js</a> and <a
href="http://npmjs.org/">Node Package Manager</a> installed.</p></blockquote><p>Before we continue on, I&#8217;ll point out that you need to have a decent knowledge of <a
href="http://coffeescript.org/">CoffeeScript</a> for this tutorial; I won&#8217;t be explaining the bits and pieces here. If you&#8217;re interested in CoffeeScript, you should check out the <a
href='http://net.tutsplus.com/tag/coffeescript/'>CoffeeScript tuts available here on Nettuts+</a>, or the <a
href='http://coffeescript.org/'>CoffeeScript documentation</a>.</p><p>Additionally, you&#8217;ll need to have Node.js and the Node Package Manager (npm) installed for this tutorial. If you don&#8217;t have &#8216;em installed, no worries: head over to <a
href='http://nodejs.org/'>nodejs.org</a> and download the installer for your platform; then, well, install it!</p><hr
/><h2>Meeting Mocha and Chai</h2><p>We&#8217;ll be building the beginnings of a todo list application (clich&eacute;, I know). These will be CoffeeScript classes. Then, we&#8217;ll write some tests with <a
href="http://visionmedia.github.com/mocha/">Mocha</a> and Chai to test that functionality.</p><p>Why both Mocha and Chai? Well, Mocha is a testing framework, but it doesn&#8217;t include the actual assertions component. That might sound strange: after all, there isn&#8217;t much more to a testing library, is there? Well, there is, in Mocha&#8217;s case. The features that brought me to the library are two-fold: the ability to run tests from the command line (instead of having an HTML page to run them in the browser), and the ability to run test in CoffeeScripts, without having to convert that code to JavaScript (as least manually: Mocha does it behind the scenes). There are other features, too, that I won&#8217;t be talking about here, including:</p><ul><li>You can easily test asynchronous code.</li><li>You can watch for especially slow tests.</li><li>You can output the results in a number of different formats.</li></ul><p>And on, and on. See more <a
href='http://visionmedia.github.com/mocha/'>at the Mocha home page</a>. To install Mocha simply run <code>npm install -g mocha</code>, and you&#8217;re set.</p><p>As for Chai: it&#8217;s a great assertion library that offers interfaces for doing both <a
href='https://en.wikipedia.org/wiki/Behavior_Driven_Development'>BDD</a> and <a
href='https://en.wikipedia.org/wiki/Test-driven_development'>TDD</a>; you can use it both in the browser or on the command line via node, which is how we&#8217;ll use it today. Install it for Node, via <code>npm install -g chai</code>.</p><p>Now that we have our libraries installed, let&#8217;s start writing some code.</p><hr
/><h2>Setting Up Our Project</h2><p>Let&#8217;s begin by setting up a mini project. Create a project folder. Then, create two more folders in that one: <code>src</code>, and <code>test</code>. Our CoffeeScript code will go in the <code>src</code> folder, and our tests will go in, you guessed it, the <code>tests</code> folder. Mocha looks for a <code>test</code> folder by default, so by doing this, we&#8217;ll save ourselves some typing later.</p><blockquote
class=pullquote><p>Mocha looks for a <code>test</code> folder by default.</p></blockquote><p>We&#8217;re going to create two CoffeeScript classes: <code>Task</code>, which will be a todo item, and <code>TaskList</code>, which will be a list of todo items (yes, it&#8217;s more than an array). We&#8217;ll put them both in the <code>src/task.coffee</code> file. Then, the tests for this will be in <code>test/taskTest.coffee</code>. Of course, we could split &#8216;em into their own files, but we&#8217;re just not going to do that today.</p><p>We have to start by importing the Chai library and enabling the BDD syntax. Here&#8217;s how:</p><pre class="js" name="code">chai = require &#39;chai&#39;
chai.should()</pre><p>By calling the <code>chai.should</code> method, we&#8217;re actually adding a <code>should</code> property to <code>Object.prototype</code>. This allows us to write tests that read like this:</p><pre class="js" name="code">task.name.should.equal &quot;some string&quot;</pre><p>If you prefer the TDD syntax, you can do this:</p><pre class="js" name="code">expect = chai.expect</pre><p>&#8230; which allows you to write tests like this:</p><pre class="js" name="code">expect(task.name).to.equal &quot;some string&quot;</pre><p>We&#8217;ll actually have to use both of these, as you&#8217;ll see; however, we&#8217;ll use the BDD syntax as much as possible.</p><p>Now we&#8217;ll need to import our <code>Task</code> and <code>TaskList</code> classes:</p><pre class="js" name="code">{TaskList, List} = require &#39;../src/task&#39;</pre><p>If you aren&#8217;t familiar with this syntax, that&#8217;s CoffeeScript&#8217;s destructured assignment at work, as well as some of its object literal sugar. Basically, our <code>require</code> call returns an object with two properties, which are our classes. This line pulls them out of that object and gives us two variables named <code>Task</code> and <code>TaskList</code>, each of which points to the respective class.</p><hr
/><h2>Writing Our First Tests</h2><p>Great! Now, how about a test? The beauty of the Mocha syntax is that its blocks (<code>describe</code> and <code>it</code>) are identical to <a
href='http://pivotal.github.com/jasmine/'>Jasmine&#8217;s</a> (both being very similar to RSpec). Here&#8217;s our first test:</p><pre class="js" name="code">describe &#39;Task instance&#39;, -&gt;
	task1 = task2 = null
	it &#39;should have a name&#39;, -&gt;
		task1 = new Task &#39;feed the cat&#39;
		task1.name.should.equal &#39;feed the cat&#39;</pre><p>We start with a <code>describe</code> call: all these tests are for a Test instance. By setting <code>test1 = test2 = null</code> outside our individual tests, we can use those values for multiple tests.</p><p>Then, in our first test, we&#8217;re simply creating a task and checking to see that its name property has the correct value. Before writing the code for this, let&#8217;s add two more tests:</p><pre class="js" name="code">it &#39;should be initially incomplete&#39;, -&gt;
	task1.status.should.equal &#39;incomplete&#39;
it &#39;should be able to be completed&#39;, -&gt;
	task1.complete().should.be.true
	task1.status.should.equal &#39;complete&#39;</pre><p>Ok, let&#8217;s run these tests to make sure they&#8217;re failing. To do this, let&#8217;s open a command prompt and <code>cd</code> to your project folder. Then, run this command:</p><pre class="js" name="code">mocha --compilers coffee:coffee-script</pre><p>Mocha doesn&#8217;t check for CoffeeScript by default, so we have to use the <code>--compilers</code> flag to tell Mocha what compiler to use if it finds a file with the <code>coffee</code> file extension. You should get errors that look like this:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/errors.png' /></div><p>If, instead of seeing that, you get the error <code>Cannot find module &#39;../src/task&#39;</code>, it&#8217;s because your <code>src/task.coffee</code> file doesn&#8217;t exist yet. Make said file, and you should get said error.</p><hr
/><h2>Coding Our First Features</h2><p>Well, now that we have failing tests, it&#8217;s time to write the code, correct? Open that <code>src/task.coffee</code> file and let&#8217;s get cracking.</p><pre class="js" name="code">class Task
	constructor: (@name) -&gt;</pre><p>Just this is enough to get our first test passing. If you aren&#8217;t familiar with that parameter syntax, that just sets whatever value was passed to <code>new Task</code> to the <code>@name</code> (or <code>this.name</code>) property. However, let&#8217;s add another line to that constructor:</p><pre class="js" name="code">@status = &#39;incomplete&#39;</pre><p>That&#8217;s good. Now, head back to the terminal and re-run our tests. You&#8217;ll find that&mdash;wait a second, nothing&#8217;s changed! Why aren&#8217;t our first two tests passing?</p><p>A simple problem, actually. Because the CoffeeScript compiler wraps the code in each file in a <a
href='http://benalman.com/news/2010/11/immediately-invoked-function-expression/'>IIFE</a> (or, a self-invoking anonymous function), we need to &#8220;export&#8221; anything we want to be accessible from other files. In the browser, you&#8217;d do something like <code>window.Whatever = Whatever</code>. For Node, you can use either <code>global</code> or <code>exports</code>. We&#8217;ll be using <code>exports</code>, since 1) that&#8217;s considered best practice, and 2) that&#8217;s what we prepared for when setting up our tests (remember our <code>require</code> call?). Therefore, at the end of our <code>task.coffee</code> file, add this:</p><pre class="js" name="code">root = exports ? window
root.Task = Task</pre><p>With that in place, you should find that two of our three tests are now passing:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/two_passing.png' /></div><p>To get the last test to pass, we&#8217;ll have to add a <code>complete</code> method. Try this:</p><pre class="js" name="code">complete: -&gt;
	@status = &#39;complete&#39;
	true</pre><p>Now, all tests pass:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/all_passing.png' /></div><p>Now&#8217;s a good time to mention that Mocha has a number of different reports: these are just different ways to output the test results. You can run <code>mocha --reporters</code> to see your options:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/reporters.png' /></div><p>By default, Mocha uses the dot reporter. However, I prefer the spec reporter, so I tack <code>-R spec</code> on the end of command (<code>-R</code> is the reporter-setting flag).</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/spec_reporter.png' /></div><hr
/><h2>Adding a Feature</h2><p>Let&#8217;s add a feature to our <code>Task</code> class: we&#8217;ll let tasks be dependent on other tasks. If the &#8220;parent&#8221; task isn&#8217;t completed, the &#8220;child&#8221; task can&#8217;t be done. We&#8217;ll keep this feature simple and allow tasks to have only one sub-task. We also won&#8217;t check for recursiveness, so while it will be possible to set two tasks to be the parent and child of each other, it will render both tasks incomplete-able.</p><p>Tests first!</p><pre class="js" name="code">it &#39;should be able to be dependent on another task&#39;, -&gt;
	task1 = new Task &#39;wash dishes&#39;
	task2 = new Task &#39;dry dishes&#39;
	task2.dependsOn task1
	task2.status.should.equal &#39;dependent&#39;
	task2.parent.should.equal task1
	task1.child.should.equal task2
it &#39;should refuse completion it is dependent on an uncompleted task&#39;, -&gt;
	(-&gt; task2.complete()).should.throw &quot;Dependent task &#39;wash dishes&#39; is not completed.&quot;</pre><p><code>Task</code> instances are going to have a <code>dependsOn</code> method, which tasks the task that will become their parent. Tasks that have a parent task should have a status of &#8220;dependent.&#8221; Also, both tasks get either a <code>parent</code> or <code>child</code> property that points to the appropriate task instance.</p><p>In the second test there, we say that a task with an incomplete parent task should throw an error when its <code>complete</code> method is called. Notice how test syntax works: we need to call <code>should</code> off of a function, and not the result of the function: therefore, we wrap the function in parentheses. This way, the test library can call the function itself and check for the error.</p><p>Run those tests and you&#8217;ll see that both fail. Coding time!</p><pre class="js" name="code">dependsOn: (@parent) -&gt;
	@parent.child = @
	@status = &#39;dependent&#39;</pre><p>Again, very simple: we just set the task parameter to the parent task, and give it a child property which points to <code>this</code> task instance. Then, we set the status of <code>this</code> task to be &#8220;dependent.&#8221;</p><p>If you run this now, you&#8217;ll see that one of our tests is passing, but the second isn&#8217;t: that&#8217;s because our <code>complete</code> method doesn&#8217;t check for an uncompleted parent task. Let&#8217;s change that.</p><pre class="js" name="code">complete: -&gt;
	if @parent? and @parent.status isnt &#39;completed&#39;
		throw &quot;Dependent task &#39;#{@parent.name}&#39; is not completed.&quot;
	@status = &#39;complete&#39;
	true</pre><p>Here&#8217;s the completed <code>complete</code> method: if there&#8217;s a parent task, and it isn&#8217;t completed, we throw an error. Otherwise, we complete the task. Now, all tests should pass.</p><hr
/><h2>Building the TaskList</h2><p>Next, we&#8217;ll build the <code>TaskList</code> class. Again, we&#8217;ll start with a test:</p><pre class="js" name="code">describe &#39;TaskList&#39;, -&gt;
    taskList = null
    it &#39;should start with no tasks&#39;, -&gt;
        taskList = new TaskList
        taskList.tasks.length.should.equal 0
        taskList.length.should.equal 0</pre><p>This is old-hat to you by now: we&#8217;re creating a <code>TaskList</code> object and checking its <code>tasks</code> and <code>length</code> properties to makes sure their both at zero. As you might guess, <code>tasks</code> is an array that holds the tasks, while <code>length</code> is just a handy property that we&#8217;ll update when adding or removing tasks; it just saves us from having to write <code>list.tasks.length</code>.</p><p>To make this test pass, we&#8217;ll make this constructor:</p><pre class="js" name="code">class TaskList
	constructor: () -&gt;
		@tasks = []
		@length = 0</pre><p>Good start, and that gets our test passing.</p><p>We&#8217;ll want to be able to add tasks to a task list, right? We&#8217;ll have an <code>add</code> method that can take either a <code>Task</code> instance, or a string which it will convert to a <code>Task</code> instance.</p><p>Our tests:</p><pre class="js" name="code">it &#39;should accept new tasks as tasks&#39;, -&gt;
    task = new Task &#39;buy milk&#39;
    taskList.add task
    taskList.tasks[0].name.should.equal &#39;buy milk&#39;
    taskList.length.should.equal 1
it &#39;should accept new tasks as string&#39;, -&gt;
    taskList.add &#39;take out garbage&#39;
    taskList.tasks[1].name.should.equal &#39;take out garbage&#39;
    taskList.length.should.equal 2</pre><p>First, we add an actual <code>Task</code> object, and check the <code>taskList.tasks</code> array to verify that it&#8217;s been added. Then, we add a string, and make sure that a <code>Task</code> object with the right name was added to the <code>tasks</code> array. In both cases, we check the length of <code>taskList</code> as well, to make sure that it&#8217;s being property updated.</p><p>And the function:</p><pre class="js" name="code">add: (task) -&gt;
    if typeof task is &#39;string&#39;
        @tasks.push new Task task
    else
        @tasks.push task
    @length = @tasks.length</pre><p>Pretty self-explanatory, I think. And now our tests pass:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/tasklist_tests.png' /></div><p>Of course, we might want to remove tasks from our list, right?</p><pre class="js" name="code">it &#39;should remove tasks&#39;, -&gt;
	i = taskList.length - 1
	taskList.remove taskList.tasks[i]
	expect(taskList.tasks[i]).to.not.be.ok</pre><p>First, we call the <code>remove</code> method (yet to be written, of course), passing it the last task currently in the list. Sure, we could just hardcode the index <code>1</code>, but I&#8217;ve done it this way because that makes this test flexible: if we changed our previous tests or added more tests above this one, that might have to change. Of course, we have to remove the last one because otherwise, the task after it will take its place and there&#8217;ll be something at that index when we&#8217;re expecting there to be nothing.</p><p>And speaking of expecting, notice that we&#8217;re using the <code>expect</code> function and syntax here instead of our usual <code>should</code>. This is because <code>taskList.tasks[i]</code> will be <code>undefined</code>, which doesn&#8217;t inherit from <code>Object.prototype</code>, and therefore we can&#8217;t use <code>should</code>.</p><p>Oh, yeah, we still need to write that <code>remove</code> function:</p><pre class="js" name="code">remove: (task) -&gt;
    i = @tasks.indexOf task
    @tasks = @tasks[0...i].concat @tasks[i+1..] if i &gt; -1
    @length = @tasks.length</pre><p>Some fancy array footwork combined with CoffeeScript&#8217;s ranges and array splicing shorthand closes this deal for us. We&#8217;re simply splitting off all the items before the one to remove and all the items after it; the we <code>concat</code> those two arrays together. Of course, we&#8217;ll update <code>@length</code> accordingly. Can you say &#8220;passing tests&#8221;?</p><p>Let&#8217;s do one more thing. We want to print our a (relatively) nice-looking list of the current tasks. This will be our most complex (or at least, our longest) test yet:</p><pre class="js" name="code">    it &#39;should print out the list&#39;, -&gt;
        taskList = new TaskList
        task0 = new Task &#39;buy milk&#39;
        task1 = new Task &#39;go to store&#39;
        task2 = new Task &#39;another task&#39;
        task3 = new Task &#39;sub-task&#39;
        task4 = new Task &#39;sub-sub-task&#39;
        taskList.add task0
        taskList.add task1
        taskList.add task2
        taskList.add task3
        taskList.add task4
        task0.dependsOn task1
        task4.dependsOn task3
        task3.dependsOn task2
        task1.complete()
        desiredOutput = &quot;&quot;&quot;Tasks
- buy milk (depends on &#39;go to store&#39;)
- go to store (completed)
- another task
- sub-task (depends on &#39;another task&#39;)
- sub-sub-task (depends on &#39;sub-task&#39;)
&quot;&quot;&quot;
		taskList.print().should.equal desiredOutput</pre><p>What&#8217;s going on here? First, we&#8217;re creating a new <code>TaskList</code> object so that we start from scratch. Then, we create five tasks and add them to <code>taskList</code>. Next, we set up a few dependencies. Finally we complete one of our tasks.</p><p>We&#8217;re using CoffeeScript&#8217;s heredoc syntax to create a multi-line string. As you can see, we&#8217;re keeping it pretty simple. If a task has a parent task, it&#8217;s mentioned in parentheses after the task name. If a task is completed, we put that, too.</p><p>Ready to write the function?</p><pre class="js" name="code">print: -&gt;
    str = &quot;Tasks\n\n&quot;
    for task in @tasks
        str += &quot;- #{task.name}&quot;
        str += &quot; (depends on &#39;#{task.parent.name}&#39;)&quot; if task.parent?
        str += &#39; (complete)&#39; if task.status is &#39;complete&#39;
        str += &quot;\n&quot;
    str</pre><p>It&#8217;s actually pretty straightforward: we just look over the <code>@tasks</code> array and add &#8216;em to a string. If they have a parent, we add that, and if they&#8217;re complete, we add that too. Notice that we&#8217;re using the modifier form of the <code>if</code> statement, to tighten up our code. Then, we return the string.</p><p>Now, all our tests should pass:</p><div
class="tutorial_image"><img
alt='' src='http://d2o0t5hpnwv4c1.cloudfront.net/2028_coffeeScriptAndMocha/all_tests.png' /></div><hr
/><h2>Wrapping Up</h2><blockquote
class=pullquote><p>Try adding a few features to get the hang of it all.</p></blockquote><p>That&#8217;s the extent of our little project today. You can download the code from the top of this page; in fact, why don&#8217;t you try adding a few features to get the hang of it all? Here are a few ideas:</p><ul><li>Prevent <code>Task</code> instances from being able to depend on each other (recursive dependencies).</li><li>Make the <code>TaskList::add</code> method throw an error if it receives something other than a string or a <code>Task</code> object.</li></ul><p>These days, I&#8217;m finding CoffeeScript more and more attractive, but the biggest downside to it is that it must be compiled to JavaScript before it&#8217;s useful. I&#8217;m grateful for anything that negates some of that workflow breaker, and Mocha definitely does that. Of course, it&#8217;s not perfect (since it&#8217;s compiling to JS before running the code, line numbers in errors don&#8217;t match up with your CoffeeScript line numbers), but it&#8217;s a step in the right direction for me!</p><p>How about you? If you&#8217;re using CoffeeScript, how have you been doing testing? Let me know in the comments.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/0/da"><img src="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/1/da"><img src="http://feedads.g.doubleclick.net/~a/Xn6aRo3l-nXuPOc9lG7EsNdjFog/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=bLERbf6u_sM:YRQGHIZep3Y:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=bLERbf6u_sM:YRQGHIZep3Y:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=bLERbf6u_sM:YRQGHIZep3Y:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=bLERbf6u_sM:YRQGHIZep3Y:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/bLERbf6u_sM" height="1" width="1"/>";s:14:"date_timestamp";i:1351778087;}i:9;a:13:{s:5:"title";s:29:"An Introduction to Handlebars";s:4:"link";s:54:"http://feedproxy.google.com/~r/nettuts/~3/YyrCd9fqaWM/";s:8:"comments";s:86:"http://net.tutsplus.com/tutorials/javascript-ajax/introduction-to-handlebars/#comments";s:7:"pubdate";s:31:"Tue, 30 Oct 2012 23:13:01 +0000";s:2:"dc";a:1:{s:7:"creator";s:16:"Gabriel Manricks";}s:8:"category";s:35:"JavaScript & AJAXhandlebarstemplate";s:4:"guid";s:32:"http://net.tutsplus.com/?p=27761";s:11:"description";s:20080:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27761&c=1661324977' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27761&c=1661324977' border='0' alt='' /></a><p>If your site&#8217;s data regularly changes, then you might want to take a look at <a
href="http://handlebarsjs.com/">Handlebars</a>. Handlebars is a template processor that dynamically generates your HTML page, saving you time from performing manual updates. In this tutorial, I&#8217;ll introduce you to Handlebars, and teach you how to create a basic template for your site.</p><p><span
id="more-27761"></span></p><hr
/><h2>Site Template</h2><p>There are two primary reasons why you&#8217;d want to make a template for your site. First of all, building a template encourages you to separate the logic-based code from the actual view, helping you adhere to a View/Controller pattern. Secondly, templates keep your code clean and maintainable, which, in turn, makes the process of updating your site a breeze. You don&#8217;t create a site with Handlebars. Instead, you create guidelines and structures that dictate how the site should look without focusing on a page&#8217;s data. Let&#8217;s cover some of the basics.</p><hr
/><h2>The Basics</h2><p>Handlebars generates your HTML by taking a JSON structure and running it through a template. These templates are written mostly in regular HTML, and are peppered with placeholders that allow you to inject data, as needed. For example, the following template greets the user when they log in:</p><pre class="brush: xml; title: ; notranslate">
&lt;h1&gt;Welcome back, {{name}}&lt;/h1&gt;
</pre><p>The <code>{{name}}</code> attribute is where the user&#8217;s name will be injected into the page. This placeholder corresponds with a property in the data&#8217;s JSON structure. This is the most basic example possible, but you will soon see that everything else basically boils down to this simple concept. Let&#8217;s move on to handling arrays.</p><h3>Arrays</h3><p>Handlebars comes with some built-in helpers to assist you in working with more complex data. One of these helpers is the <code>each</code> helper. This helper iterates through an array and allows you to create dynamic HTML, per array element. For example, the following template displays an array&#8217;s data that contains a list of the local concerts playing in my area:</p><pre class="brush: xml; title: ; notranslate">
&lt;table&gt;
	&lt;tr&gt;
		&lt;th&gt;Local Concerts&lt;/th&gt;
	&lt;/tr&gt;
	{{#each Concerts}}
		&lt;tr&gt;
			&lt;td&gt;{{this}}&lt;/td&gt;
		&lt;/tr&gt;
	{{/each}}
&lt;/table&gt;
</pre><p>As you can see, this code is much cleaner than conventional code, such as using a loop in PHP or JavaScript to append HTML to a variable. Handlebars is not intrusive, and this is what makes Handlebars so accessible. You may also notice that we use the attribute name, <code>this</code>, to retrieve the current array element in the <code>each</code> loop.</p><p>This example is good for an array of simple values, but how do you handle more complex data? Well, you essentially do the same thing. For example, we&#8217;re going to write a template for the following data:</p><pre class="brush: jscript; title: ; notranslate">
[
	{
		Name : &quot;Band&quot;,
		Date : &quot;Aug 14th, 2012&quot;,
		Albums : [
			{
				Name : &quot;Generic Name&quot;
			},
			{
				Name : &quot;Something Else!!&quot;
			}
		]
	},
	{
		Name : &quot;Other Guys&quot;,
		Date : &quot;Aug 22nd, 2012&quot;
		Albums : [
			{
				Name : &quot;Album One&quot;
			}
		]
	}
]
</pre><p>We can easily display this information using the following template:</p><pre class="brush: xml; title: ; notranslate">
&lt;table&gt;
	&lt;tr&gt;
		&lt;th&gt;Band Name&lt;/th&gt;
		&lt;th&gt;Date&lt;/th&gt;
		&lt;th&gt;Album Name&lt;/th&gt;
	&lt;/tr&gt;
	{{#each Bands}}
		&lt;tr&gt;
			&lt;td&gt;{{Name}}&lt;/td&gt;
			&lt;td&gt;{{Date}}&lt;/td&gt;
			&lt;td&gt;{{Albums.0.Name}}&lt;/td&gt;
		&lt;/tr&gt;
	{{/each}}
&lt;/table&gt;
</pre><blockquote
class="pullquote"><p>You can store your template in a <code>&lt;script /&gt;</code> element and load it with JavaScript.</p></blockquote><p>In Handlebars, you can even access nested properties, like in the example above (<code>Albums.0.Name</code>), and of course, you could have used another <code>each</code> loop to iterate over a band&#8217;s albums. It&#8217;s worth noting that besides the dot notation to access nested properties, you can also use &#8220;../&#8221; to access a parent&#8217;s properties.</p><p>What if there aren&#8217;t any bands playing? You certainly don&#8217;t want an empty table, and Handlebars thankfully provides <code>if</code>, <code>else</code> and <code>unless</code> helpers. The <code>if</code> and <code>else</code> statements work like most programming languages: if the object you pass is <code>false</code> or falsey, then the <code>else</code> statement executes. Otherwise, the <code>if</code> statement executes. The <code>unless</code> statement is pretty interesting; it&#8217;s essentially an inverted <code>if</code> statement. If the expression is <code>true</code>, the <code>unless</code> block will NOT run. So let&#8217;s incorporate these helpers into our code:</p><pre class="brush: xml; title: ; notranslate">
{{#if Bands}}
	&lt;table&gt;
		&lt;tr&gt;
			&lt;th&gt;Band Name&lt;/th&gt;
			&lt;th&gt;Date&lt;/th&gt;
			&lt;th&gt;Album Name&lt;/th&gt;
		&lt;/tr&gt;
		{{#each Bands}}
			&lt;tr&gt;
				&lt;td&gt;{{Name}}&lt;/td&gt;
				&lt;td&gt;{{Date}}&lt;/td&gt;
				&lt;td&gt;{{Albums.0.Name}}&lt;/td&gt;
			&lt;/tr&gt;
		{{/each}}
	&lt;/table&gt;
{{else}}
	&lt;h3&gt;There are no concerts coming up.&lt;/h3&gt;
{{/if}}
</pre><h3>Custom Helpers</h3><p>Handlebars gives you the ability to create your own custom helper. Simply register your function into Handlebars, and any template you compile afterwards can access your helper. There are two kinds of helpers that you can make:</p><ul><li><strong>Function helpers</strong> are basically regular functions that, once registered, can be called anywhere in your template. Handlebars writes the function&#8217;s return value into the template.</li><li><strong>Block helpers</strong> are similar in nature to the <code>if</code>, <code>each</code>, etc. helpers. They allow you to change the context of what&#8217;s inside.</li></ul><p>Let me show you a quick example of each. First, I&#8217;ll register a function helper with the following code:</p><pre class="brush: jscript; title: ; notranslate">
Handlebars.registerHelper(&quot;Max&quot;, function(A, B){
	return (A &gt; B) ? A : B;
});
</pre><p>The first argument passed to <code>registerHelper()</code> is the name of my customer helper; I&#8217;ll use this name in the template. The second argument is the function associated with this helper.</p><p>Using this helper in a template is extremely simple:</p><pre class="brush: xml; title: ; notranslate">
{{Max 12 45}}
</pre><p>This template uses the <code>Max</code> helper, and passes the values 12 and 45 to the associated function. Handlebars function helpers support multiple parameters. You can directly insert numbers into the template itself, or you can use attributes from a JSON structure.</p><p>Now let&#8217;s look at a custom block helper. Block helpers allow you to set the context before running the code contained within the block. For example, consider the following object:</p><pre class="brush: jscript; title: ; notranslate">
{
	Name: &quot;Parent&quot;,
	Sub: {
		Name: &quot;Child&quot;
	}
}
</pre><p>In order to display both names, you can write a block helper that runs the template once with the parent&#8217;s context, and once with the child&#8217;s context. Here is the helper:</p><pre class="brush: jscript; title: ; notranslate">
Handlebars.registerHelper(&quot;BothNames&quot;, function(context, options){
	return options.fn(context) + options.fn(context.Sub);
});
</pre><p>And the template looks like this:</p><pre class="brush: xml; title: ; notranslate">
{{#BothNames this}}
	&lt;h2&gt;{{Name}}&lt;/h2&gt;
{{/BothName}}
</pre><p>The hash tag before the helper&#8217;s name tells Handlebars that this is a block helper, and you close the block not unlike you would an HTML tag. The <code>options.fn</code> function runs the section of template inside the block with whatever context you give it.</p><p>Now that we have the basics down, let&#8217;s start creating a full demo.</p><hr
/><h2>Building a Site Template</h2><blockquote
class="pullquote"><p>You don&#8217;t create a site with Handlebars.</p></blockquote><p>The template we will build is for a recipe site. This will give you a good understanding of Handlebars, as it encompasses getting data from an API and passing it through a template.</p><h3>Setting up a Handlebars project</h3><p>We must first load our template script, but in order to do that, we need to create a new HTML file and include our Handlebars library:</p><pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Handlebars Demo&lt;/title&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;Handlebars.js&quot;&gt;&lt;/script&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;script id=&quot;Handlebars-Template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
		&lt;/script&gt;
	&lt;/body&gt;
&lt;/html&gt;
</pre><p>For convenience, you can store your template in a <code>&lt;script /&gt;</code> element and load it with JavaScript. This is much cleaner than storing it directly in a JavaScript variable.</p><p>Now let&#8217;s discuss how this app is going to work. First, the app connects to an API (I&#8217;m using Yummly) to pull in information on some recipes. Next, we pass this info to Handlebars and run it through the template. Finally, we replace the body section with the newly generated HTML. It&#8217;s a fairly straight forward process; so, let&#8217;s start by adding a second <code>script</code> block right before the closing <code>body</code> tag, and instantiate an <code>Ajax</code> variable:</p><pre class="brush: xml; title: ; notranslate">
&lt;script&gt;
var Ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
Ajax.onreadystatechange = function(){
	if (Ajax.readyState == 4 &amp;&amp; Ajax.status == 200)
	{
		//Parse the JSON data
		var RecipeData = JSON.parse(Ajax.responseText);
		//Get the Template from above
		var Source = document.getElementById(&quot;Handlebars-Template&quot;).textContent;
		//Compile the actual Template file
		var Template = Handlebars.compile(Source);
		//Generate some HTML code from the compiled Template
		var HTML = Template({ Recipes : RecipeData });
		//Replace the body section with the new code.
		document.body.innerHTML = HTML;
	}
}
Ajax.open(&quot;GET&quot;,&quot;Recipe.php&quot;, true);
Ajax.send();
&lt;/script&gt;
</pre><blockquote
class="pullquote"><p>If your site’s data regularly changes, then you might want to take a look at Handlebars.</p></blockquote><p>This is the complete code for compiling and generating HTML code from a template. You can technically pass the JSON data from the API directly into Handlebars, but you run into cross origin issues. Instead of performing some sort of hack or using PHP to &#8220;echo&#8221; the data into a JavaScript variable, I decided to put all of that into a separate file: <code>Recipe.php</code>. So before we start building the template, let&#8217;s go take a look at that PHP file.</p><h3>Getting The Data</h3><p>The Yummly API is pretty simple. There is no elaborate authentication system; you just have to sign up, get some credentials, and insert them into the URL. You can directly echo the data if you want to, but I want a bit more detailed info on each recipe. Therefore, I will process the data from the first API call and make a second request for every recipe. Here is the complete PHP script:</p><pre class="brush: php; title: ; notranslate">
&lt;?php
	//Empty Array to hold all the recipes
	$Json = [];
	$UserID = //Your ID Here;
	$UserKey = //Your Yummly key;
	//This searches Yummly for cake recipes
	$Recipes = file_get_contents(&quot;http://api.yummly.com/v1/api/recipes?_app_id=&quot; . $UserID . &quot;&amp;_app_key=&quot; . $UserKey . &quot;&amp;maxResult=2&amp;requirePictures=true&amp;q=Cake&quot;);
	//Decode the JSON into a php object
	$Recipes = json_decode($Recipes)-&gt;matches;
	//Cycle Through The Recipes and Get full recipe for each
	foreach($Recipes as $Recipe)
	{
		$ID = $Recipe-&gt;id;
		$R = json_decode(file_get_contents(&quot;http://api.yummly.com/v1/api/recipe/&quot; . $ID . &quot;?_app_id=&quot; . $UserID . &quot;&amp;_app_key=&quot; . $UserKey . &quot;&amp;images=large&quot;));
		//This is the data we are going to pass to our Template
		array_push($Json, array(
			Name =&gt; $R-&gt;name,
			Ingredients =&gt; $R-&gt;ingredientLines,
			Image =&gt; $R-&gt;images[0]-&gt;hostedLargeUrl,
			Yield =&gt; $R-&gt;yield,
			Flavors =&gt; $R-&gt;flavors,
			Source =&gt; array(
				Name =&gt; $R-&gt;source-&gt;sourceDisplayName,
				Url =&gt; $R-&gt;source-&gt;sourceRecipeUrl
			)
		));
	}
	//Print out the final JSON object
	echo json_encode($Json);
?&gt;
</pre><p>By building your site with a Handlebars template, you can produce a full site&#8217;s worth of code in only a few lines. Here is the entire template:</p><pre class="brush: xml; title: ; notranslate">
&lt;script id=&quot;Handlebars-Template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
	&lt;div id=&quot;Content&quot;&gt;
	  &lt;h1&gt;&amp;Xi;RecipeCards
	  	&lt;span id='BOS'&gt;Recipe search powered by
	  		&lt;a id='Logo' href='http://www.yummly.com/recipes'&gt;
	  			&lt;img src='http://static.yummly.com/api-logo.png'/&gt;
	  		&lt;/a&gt;
	  	&lt;/span&gt;
	  &lt;/h1&gt;
	  {{#each Recipes}}
	  	&lt;div class='Box'&gt;
		  	&lt;img class='Thumb' src=&quot;{{{Image}}}&quot; alt=&quot;{{Name}}&quot;&gt;
		  	&lt;h3&gt;{{Name}} &lt;a id='Logo' href=&quot;{{Source.Url}}&quot;&gt; - {{Source.Name}}&lt;/a&gt;&lt;/h3&gt;
		  	&lt;h5&gt;{{getFlavor Flavors}}&lt;/h5&gt;
		  	&lt;h5&gt;{{Yield}}&lt;/h5&gt;
		  	&lt;p&gt;Ingredients:&lt;/p&gt;
		  	&lt;ul&gt;
		  		{{#each Ingredients}}
		  			&lt;li&gt;{{this}}&lt;/li&gt;
		  		{{/each}}
		  	&lt;/ul&gt;
	  	&lt;/div&gt;
	  {{/each}}
	&lt;/div&gt;
&lt;/script&gt;
</pre><p>Let&#8217;s run through this code. The first seven lines are just the logo at the top of the page. Then for each recipe, we create a recipe &#8216;card&#8217; with a picture, name, and ingredients.</p><p>The Yummly API returns a list of flavor data (i.e. how sweet, sour, spicy, etc..) for each item. I wrote a function helper, called <code>getFlavor</code> that takes this info and returns the most dominant flavor in the dish. In order for this template to work, we need to load in the <code>getFlavor</code> helper into Handlebars before parsing the template. So at the beginning of the second script section, add the following code before the Ajax code:</p><pre class="brush: jscript; title: ; notranslate">
Handlebars.registerHelper(&quot;getFlavor&quot;, function(FlavorsArr){
	var H = 0;
	var Name = '';
	for(var F in FlavorsArr)
	{
		if(FlavorsArr[F] &gt; H)
		{
			H = FlavorsArr[F];
			Name = F;
		}
	}
	return &quot;This Dish has a &quot; + Name + &quot; Flavor&quot;;
});
</pre><p>Now, whenever Handlebars sees <code>getFlavor</code>, it calls the associated function and retrieves the flavor information.</p><p>At this point, you are free to play around and design the template however you wish, but you will most likely see that this process is slow. This is primarily due to the three API calls before Handlebars loads the page. Obviously, this is not ideal, but precompiling your template can help.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2143_handlebars/Pic1.png" border="0" /></div><hr
/><h2>Precompiling</h2><p>You have two different options, when it comes to Handlebars. The first is to just precompile the actual template. This reduces the loading time, and you won&#8217;t have to include the Handlebars compiler with your page.</p><blockquote><p>This also results in a smaller file size, but this doesn&#8217;t really help in our scenario.</p></blockquote><p>Our problem is the communication between the browser and the API. If you did want to precompile your template, you can download the Node.js package through <code>npm</code> with the following command:</p><pre class="brush: bash; title: ; notranslate">
npm install handlebars -g
</pre><p>You may need to do this as root (i.e. add &#8216;sudo&#8217; before the command). Once installed, you can create a file for your template and compile it like so:</p><pre class="brush: bash; title: ; notranslate">
handlebars demo.handlebars -f demo.js
</pre><p>You should give your template file a <code>.handlebars</code> extension. This is not mandatory, but if you name it something like <code>demo.html</code>, then the template&#8217;s name will be &#8220;demo.html&#8221; as apposed to just &#8220;demo&#8221;. After naming your template, simply include the output file along with the run-time version of Handlebars (you can use the regular version, but it&#8217;s larger) and type the following:</p><pre class="brush: jscript; title: ; notranslate">
var template = Handlebars.templates['demo'];
var html = template({ Your Json Data Here });
</pre><blockquote
class="pullquote"><p>The <code>unless</code> statement is&#8230;essentially an inverted <code>if</code> statement.</p></blockquote><p>But, as I mentioned before, this doesn&#8217;t really help us in this scenario. What then can we do? Well, we can precompile and output the entire file. This makes it so that we can run the template with data and save the final HTML output &#8211; caching, in other words. This drastically speeds up the load time of your application. Unfortunately, client-side JavaScript doesn&#8217;t have file IO capabilities. So, the easiest way to accomplish this is to just output the HTML to a text box and manually save it. Be aware of an API&#8217;s guidelines on caching. Most APIs have a maximum amount of time that data can be cached for; make sure to find that information before saving static pages.</p><hr
/><h2>Conclusion</h2><p>This has been a quick introduction to Handlebars. Moving forward, you can look into &#8220;Partials&#8221; &#8211; small templates that can be used like functions. As always, feel free to leave a comment or question in the comment section below.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/0/da"><img src="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/1/da"><img src="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=YyrCd9fqaWM:hur-gsJ3Cyc:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=YyrCd9fqaWM:hur-gsJ3Cyc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=YyrCd9fqaWM:hur-gsJ3Cyc:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/YyrCd9fqaWM" height="1" width="1"/>";s:3:"wfw";a:1:{s:10:"commentrss";s:82:"http://net.tutsplus.com/tutorials/javascript-ajax/introduction-to-handlebars/feed/";}s:5:"slash";a:1:{s:8:"comments";s:2:"34";}s:10:"feedburner";a:1:{s:8:"origlink";s:77:"http://net.tutsplus.com/tutorials/javascript-ajax/introduction-to-handlebars/";}s:7:"summary";s:20080:"<a
href='http://rss.buysellads.com/click.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27761&c=1661324977' target='_blank'><img
src='http://rss.buysellads.com/img.php?z=1260013&k=d754f1e9ba63a736ba8ff5ece958f7dd&a=27761&c=1661324977' border='0' alt='' /></a><p>If your site&#8217;s data regularly changes, then you might want to take a look at <a
href="http://handlebarsjs.com/">Handlebars</a>. Handlebars is a template processor that dynamically generates your HTML page, saving you time from performing manual updates. In this tutorial, I&#8217;ll introduce you to Handlebars, and teach you how to create a basic template for your site.</p><p><span
id="more-27761"></span></p><hr
/><h2>Site Template</h2><p>There are two primary reasons why you&#8217;d want to make a template for your site. First of all, building a template encourages you to separate the logic-based code from the actual view, helping you adhere to a View/Controller pattern. Secondly, templates keep your code clean and maintainable, which, in turn, makes the process of updating your site a breeze. You don&#8217;t create a site with Handlebars. Instead, you create guidelines and structures that dictate how the site should look without focusing on a page&#8217;s data. Let&#8217;s cover some of the basics.</p><hr
/><h2>The Basics</h2><p>Handlebars generates your HTML by taking a JSON structure and running it through a template. These templates are written mostly in regular HTML, and are peppered with placeholders that allow you to inject data, as needed. For example, the following template greets the user when they log in:</p><pre class="brush: xml; title: ; notranslate">
&lt;h1&gt;Welcome back, {{name}}&lt;/h1&gt;
</pre><p>The <code>{{name}}</code> attribute is where the user&#8217;s name will be injected into the page. This placeholder corresponds with a property in the data&#8217;s JSON structure. This is the most basic example possible, but you will soon see that everything else basically boils down to this simple concept. Let&#8217;s move on to handling arrays.</p><h3>Arrays</h3><p>Handlebars comes with some built-in helpers to assist you in working with more complex data. One of these helpers is the <code>each</code> helper. This helper iterates through an array and allows you to create dynamic HTML, per array element. For example, the following template displays an array&#8217;s data that contains a list of the local concerts playing in my area:</p><pre class="brush: xml; title: ; notranslate">
&lt;table&gt;
	&lt;tr&gt;
		&lt;th&gt;Local Concerts&lt;/th&gt;
	&lt;/tr&gt;
	{{#each Concerts}}
		&lt;tr&gt;
			&lt;td&gt;{{this}}&lt;/td&gt;
		&lt;/tr&gt;
	{{/each}}
&lt;/table&gt;
</pre><p>As you can see, this code is much cleaner than conventional code, such as using a loop in PHP or JavaScript to append HTML to a variable. Handlebars is not intrusive, and this is what makes Handlebars so accessible. You may also notice that we use the attribute name, <code>this</code>, to retrieve the current array element in the <code>each</code> loop.</p><p>This example is good for an array of simple values, but how do you handle more complex data? Well, you essentially do the same thing. For example, we&#8217;re going to write a template for the following data:</p><pre class="brush: jscript; title: ; notranslate">
[
	{
		Name : &quot;Band&quot;,
		Date : &quot;Aug 14th, 2012&quot;,
		Albums : [
			{
				Name : &quot;Generic Name&quot;
			},
			{
				Name : &quot;Something Else!!&quot;
			}
		]
	},
	{
		Name : &quot;Other Guys&quot;,
		Date : &quot;Aug 22nd, 2012&quot;
		Albums : [
			{
				Name : &quot;Album One&quot;
			}
		]
	}
]
</pre><p>We can easily display this information using the following template:</p><pre class="brush: xml; title: ; notranslate">
&lt;table&gt;
	&lt;tr&gt;
		&lt;th&gt;Band Name&lt;/th&gt;
		&lt;th&gt;Date&lt;/th&gt;
		&lt;th&gt;Album Name&lt;/th&gt;
	&lt;/tr&gt;
	{{#each Bands}}
		&lt;tr&gt;
			&lt;td&gt;{{Name}}&lt;/td&gt;
			&lt;td&gt;{{Date}}&lt;/td&gt;
			&lt;td&gt;{{Albums.0.Name}}&lt;/td&gt;
		&lt;/tr&gt;
	{{/each}}
&lt;/table&gt;
</pre><blockquote
class="pullquote"><p>You can store your template in a <code>&lt;script /&gt;</code> element and load it with JavaScript.</p></blockquote><p>In Handlebars, you can even access nested properties, like in the example above (<code>Albums.0.Name</code>), and of course, you could have used another <code>each</code> loop to iterate over a band&#8217;s albums. It&#8217;s worth noting that besides the dot notation to access nested properties, you can also use &#8220;../&#8221; to access a parent&#8217;s properties.</p><p>What if there aren&#8217;t any bands playing? You certainly don&#8217;t want an empty table, and Handlebars thankfully provides <code>if</code>, <code>else</code> and <code>unless</code> helpers. The <code>if</code> and <code>else</code> statements work like most programming languages: if the object you pass is <code>false</code> or falsey, then the <code>else</code> statement executes. Otherwise, the <code>if</code> statement executes. The <code>unless</code> statement is pretty interesting; it&#8217;s essentially an inverted <code>if</code> statement. If the expression is <code>true</code>, the <code>unless</code> block will NOT run. So let&#8217;s incorporate these helpers into our code:</p><pre class="brush: xml; title: ; notranslate">
{{#if Bands}}
	&lt;table&gt;
		&lt;tr&gt;
			&lt;th&gt;Band Name&lt;/th&gt;
			&lt;th&gt;Date&lt;/th&gt;
			&lt;th&gt;Album Name&lt;/th&gt;
		&lt;/tr&gt;
		{{#each Bands}}
			&lt;tr&gt;
				&lt;td&gt;{{Name}}&lt;/td&gt;
				&lt;td&gt;{{Date}}&lt;/td&gt;
				&lt;td&gt;{{Albums.0.Name}}&lt;/td&gt;
			&lt;/tr&gt;
		{{/each}}
	&lt;/table&gt;
{{else}}
	&lt;h3&gt;There are no concerts coming up.&lt;/h3&gt;
{{/if}}
</pre><h3>Custom Helpers</h3><p>Handlebars gives you the ability to create your own custom helper. Simply register your function into Handlebars, and any template you compile afterwards can access your helper. There are two kinds of helpers that you can make:</p><ul><li><strong>Function helpers</strong> are basically regular functions that, once registered, can be called anywhere in your template. Handlebars writes the function&#8217;s return value into the template.</li><li><strong>Block helpers</strong> are similar in nature to the <code>if</code>, <code>each</code>, etc. helpers. They allow you to change the context of what&#8217;s inside.</li></ul><p>Let me show you a quick example of each. First, I&#8217;ll register a function helper with the following code:</p><pre class="brush: jscript; title: ; notranslate">
Handlebars.registerHelper(&quot;Max&quot;, function(A, B){
	return (A &gt; B) ? A : B;
});
</pre><p>The first argument passed to <code>registerHelper()</code> is the name of my customer helper; I&#8217;ll use this name in the template. The second argument is the function associated with this helper.</p><p>Using this helper in a template is extremely simple:</p><pre class="brush: xml; title: ; notranslate">
{{Max 12 45}}
</pre><p>This template uses the <code>Max</code> helper, and passes the values 12 and 45 to the associated function. Handlebars function helpers support multiple parameters. You can directly insert numbers into the template itself, or you can use attributes from a JSON structure.</p><p>Now let&#8217;s look at a custom block helper. Block helpers allow you to set the context before running the code contained within the block. For example, consider the following object:</p><pre class="brush: jscript; title: ; notranslate">
{
	Name: &quot;Parent&quot;,
	Sub: {
		Name: &quot;Child&quot;
	}
}
</pre><p>In order to display both names, you can write a block helper that runs the template once with the parent&#8217;s context, and once with the child&#8217;s context. Here is the helper:</p><pre class="brush: jscript; title: ; notranslate">
Handlebars.registerHelper(&quot;BothNames&quot;, function(context, options){
	return options.fn(context) + options.fn(context.Sub);
});
</pre><p>And the template looks like this:</p><pre class="brush: xml; title: ; notranslate">
{{#BothNames this}}
	&lt;h2&gt;{{Name}}&lt;/h2&gt;
{{/BothName}}
</pre><p>The hash tag before the helper&#8217;s name tells Handlebars that this is a block helper, and you close the block not unlike you would an HTML tag. The <code>options.fn</code> function runs the section of template inside the block with whatever context you give it.</p><p>Now that we have the basics down, let&#8217;s start creating a full demo.</p><hr
/><h2>Building a Site Template</h2><blockquote
class="pullquote"><p>You don&#8217;t create a site with Handlebars.</p></blockquote><p>The template we will build is for a recipe site. This will give you a good understanding of Handlebars, as it encompasses getting data from an API and passing it through a template.</p><h3>Setting up a Handlebars project</h3><p>We must first load our template script, but in order to do that, we need to create a new HTML file and include our Handlebars library:</p><pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Handlebars Demo&lt;/title&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;Handlebars.js&quot;&gt;&lt;/script&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;script id=&quot;Handlebars-Template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
		&lt;/script&gt;
	&lt;/body&gt;
&lt;/html&gt;
</pre><p>For convenience, you can store your template in a <code>&lt;script /&gt;</code> element and load it with JavaScript. This is much cleaner than storing it directly in a JavaScript variable.</p><p>Now let&#8217;s discuss how this app is going to work. First, the app connects to an API (I&#8217;m using Yummly) to pull in information on some recipes. Next, we pass this info to Handlebars and run it through the template. Finally, we replace the body section with the newly generated HTML. It&#8217;s a fairly straight forward process; so, let&#8217;s start by adding a second <code>script</code> block right before the closing <code>body</code> tag, and instantiate an <code>Ajax</code> variable:</p><pre class="brush: xml; title: ; notranslate">
&lt;script&gt;
var Ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
Ajax.onreadystatechange = function(){
	if (Ajax.readyState == 4 &amp;&amp; Ajax.status == 200)
	{
		//Parse the JSON data
		var RecipeData = JSON.parse(Ajax.responseText);
		//Get the Template from above
		var Source = document.getElementById(&quot;Handlebars-Template&quot;).textContent;
		//Compile the actual Template file
		var Template = Handlebars.compile(Source);
		//Generate some HTML code from the compiled Template
		var HTML = Template({ Recipes : RecipeData });
		//Replace the body section with the new code.
		document.body.innerHTML = HTML;
	}
}
Ajax.open(&quot;GET&quot;,&quot;Recipe.php&quot;, true);
Ajax.send();
&lt;/script&gt;
</pre><blockquote
class="pullquote"><p>If your site’s data regularly changes, then you might want to take a look at Handlebars.</p></blockquote><p>This is the complete code for compiling and generating HTML code from a template. You can technically pass the JSON data from the API directly into Handlebars, but you run into cross origin issues. Instead of performing some sort of hack or using PHP to &#8220;echo&#8221; the data into a JavaScript variable, I decided to put all of that into a separate file: <code>Recipe.php</code>. So before we start building the template, let&#8217;s go take a look at that PHP file.</p><h3>Getting The Data</h3><p>The Yummly API is pretty simple. There is no elaborate authentication system; you just have to sign up, get some credentials, and insert them into the URL. You can directly echo the data if you want to, but I want a bit more detailed info on each recipe. Therefore, I will process the data from the first API call and make a second request for every recipe. Here is the complete PHP script:</p><pre class="brush: php; title: ; notranslate">
&lt;?php
	//Empty Array to hold all the recipes
	$Json = [];
	$UserID = //Your ID Here;
	$UserKey = //Your Yummly key;
	//This searches Yummly for cake recipes
	$Recipes = file_get_contents(&quot;http://api.yummly.com/v1/api/recipes?_app_id=&quot; . $UserID . &quot;&amp;_app_key=&quot; . $UserKey . &quot;&amp;maxResult=2&amp;requirePictures=true&amp;q=Cake&quot;);
	//Decode the JSON into a php object
	$Recipes = json_decode($Recipes)-&gt;matches;
	//Cycle Through The Recipes and Get full recipe for each
	foreach($Recipes as $Recipe)
	{
		$ID = $Recipe-&gt;id;
		$R = json_decode(file_get_contents(&quot;http://api.yummly.com/v1/api/recipe/&quot; . $ID . &quot;?_app_id=&quot; . $UserID . &quot;&amp;_app_key=&quot; . $UserKey . &quot;&amp;images=large&quot;));
		//This is the data we are going to pass to our Template
		array_push($Json, array(
			Name =&gt; $R-&gt;name,
			Ingredients =&gt; $R-&gt;ingredientLines,
			Image =&gt; $R-&gt;images[0]-&gt;hostedLargeUrl,
			Yield =&gt; $R-&gt;yield,
			Flavors =&gt; $R-&gt;flavors,
			Source =&gt; array(
				Name =&gt; $R-&gt;source-&gt;sourceDisplayName,
				Url =&gt; $R-&gt;source-&gt;sourceRecipeUrl
			)
		));
	}
	//Print out the final JSON object
	echo json_encode($Json);
?&gt;
</pre><p>By building your site with a Handlebars template, you can produce a full site&#8217;s worth of code in only a few lines. Here is the entire template:</p><pre class="brush: xml; title: ; notranslate">
&lt;script id=&quot;Handlebars-Template&quot; type=&quot;text/x-handlebars-template&quot;&gt;
	&lt;div id=&quot;Content&quot;&gt;
	  &lt;h1&gt;&amp;Xi;RecipeCards
	  	&lt;span id='BOS'&gt;Recipe search powered by
	  		&lt;a id='Logo' href='http://www.yummly.com/recipes'&gt;
	  			&lt;img src='http://static.yummly.com/api-logo.png'/&gt;
	  		&lt;/a&gt;
	  	&lt;/span&gt;
	  &lt;/h1&gt;
	  {{#each Recipes}}
	  	&lt;div class='Box'&gt;
		  	&lt;img class='Thumb' src=&quot;{{{Image}}}&quot; alt=&quot;{{Name}}&quot;&gt;
		  	&lt;h3&gt;{{Name}} &lt;a id='Logo' href=&quot;{{Source.Url}}&quot;&gt; - {{Source.Name}}&lt;/a&gt;&lt;/h3&gt;
		  	&lt;h5&gt;{{getFlavor Flavors}}&lt;/h5&gt;
		  	&lt;h5&gt;{{Yield}}&lt;/h5&gt;
		  	&lt;p&gt;Ingredients:&lt;/p&gt;
		  	&lt;ul&gt;
		  		{{#each Ingredients}}
		  			&lt;li&gt;{{this}}&lt;/li&gt;
		  		{{/each}}
		  	&lt;/ul&gt;
	  	&lt;/div&gt;
	  {{/each}}
	&lt;/div&gt;
&lt;/script&gt;
</pre><p>Let&#8217;s run through this code. The first seven lines are just the logo at the top of the page. Then for each recipe, we create a recipe &#8216;card&#8217; with a picture, name, and ingredients.</p><p>The Yummly API returns a list of flavor data (i.e. how sweet, sour, spicy, etc..) for each item. I wrote a function helper, called <code>getFlavor</code> that takes this info and returns the most dominant flavor in the dish. In order for this template to work, we need to load in the <code>getFlavor</code> helper into Handlebars before parsing the template. So at the beginning of the second script section, add the following code before the Ajax code:</p><pre class="brush: jscript; title: ; notranslate">
Handlebars.registerHelper(&quot;getFlavor&quot;, function(FlavorsArr){
	var H = 0;
	var Name = '';
	for(var F in FlavorsArr)
	{
		if(FlavorsArr[F] &gt; H)
		{
			H = FlavorsArr[F];
			Name = F;
		}
	}
	return &quot;This Dish has a &quot; + Name + &quot; Flavor&quot;;
});
</pre><p>Now, whenever Handlebars sees <code>getFlavor</code>, it calls the associated function and retrieves the flavor information.</p><p>At this point, you are free to play around and design the template however you wish, but you will most likely see that this process is slow. This is primarily due to the three API calls before Handlebars loads the page. Obviously, this is not ideal, but precompiling your template can help.</p><div
class="tutorial_image"><img
src="http://d2o0t5hpnwv4c1.cloudfront.net/2143_handlebars/Pic1.png" border="0" /></div><hr
/><h2>Precompiling</h2><p>You have two different options, when it comes to Handlebars. The first is to just precompile the actual template. This reduces the loading time, and you won&#8217;t have to include the Handlebars compiler with your page.</p><blockquote><p>This also results in a smaller file size, but this doesn&#8217;t really help in our scenario.</p></blockquote><p>Our problem is the communication between the browser and the API. If you did want to precompile your template, you can download the Node.js package through <code>npm</code> with the following command:</p><pre class="brush: bash; title: ; notranslate">
npm install handlebars -g
</pre><p>You may need to do this as root (i.e. add &#8216;sudo&#8217; before the command). Once installed, you can create a file for your template and compile it like so:</p><pre class="brush: bash; title: ; notranslate">
handlebars demo.handlebars -f demo.js
</pre><p>You should give your template file a <code>.handlebars</code> extension. This is not mandatory, but if you name it something like <code>demo.html</code>, then the template&#8217;s name will be &#8220;demo.html&#8221; as apposed to just &#8220;demo&#8221;. After naming your template, simply include the output file along with the run-time version of Handlebars (you can use the regular version, but it&#8217;s larger) and type the following:</p><pre class="brush: jscript; title: ; notranslate">
var template = Handlebars.templates['demo'];
var html = template({ Your Json Data Here });
</pre><blockquote
class="pullquote"><p>The <code>unless</code> statement is&#8230;essentially an inverted <code>if</code> statement.</p></blockquote><p>But, as I mentioned before, this doesn&#8217;t really help us in this scenario. What then can we do? Well, we can precompile and output the entire file. This makes it so that we can run the template with data and save the final HTML output &#8211; caching, in other words. This drastically speeds up the load time of your application. Unfortunately, client-side JavaScript doesn&#8217;t have file IO capabilities. So, the easiest way to accomplish this is to just output the HTML to a text box and manually save it. Be aware of an API&#8217;s guidelines on caching. Most APIs have a maximum amount of time that data can be cached for; make sure to find that information before saving static pages.</p><hr
/><h2>Conclusion</h2><p>This has been a quick introduction to Handlebars. Moving forward, you can look into &#8220;Partials&#8221; &#8211; small templates that can be used like functions. As always, feel free to leave a comment or question in the comment section below.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/0/da"><img src="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/1/da"><img src="http://feedads.g.doubleclick.net/~a/Whvfp249rVFDseh2_RzvFVB-HeQ/1/di" border="0" ismap="true"></img></a></p><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/nettuts?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/nettuts?i=YyrCd9fqaWM:hur-gsJ3Cyc:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/nettuts?i=YyrCd9fqaWM:hur-gsJ3Cyc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/nettuts?i=YyrCd9fqaWM:hur-gsJ3Cyc:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/nettuts?a=YyrCd9fqaWM:hur-gsJ3Cyc:TzevzKxY174"><img src="http://feeds.feedburner.com/~ff/nettuts?d=TzevzKxY174" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/nettuts/~4/YyrCd9fqaWM" height="1" width="1"/>";s:14:"date_timestamp";i:1351638781;}}s:7:"channel";a:8:{s:5:"title";s:8:"Nettuts+";s:4:"link";s:23:"http://net.tutsplus.com";s:11:"description";s:34:"Web Development & Design Tutorials";s:13:"lastbuilddate";s:31:"Tue, 13 Nov 2012 17:00:25 +0000";s:2:"sy";a:2:{s:12:"updateperiod";s:6:"hourly";s:15:"updatefrequency";s:1:"1";}s:9:"generator";s:29:"http://wordpress.org/?v=3.4.1";s:10:"feedburner";a:2:{s:14:"emailserviceid";s:7:"nettuts";s:18:"feedburnerhostname";s:28:"http://feedburner.google.com";}s:7:"tagline";s:34:"Web Development & Design Tutorials";}s:9:"textinput";a:0:{}s:5:"image";a:3:{s:4:"link";s:18:"http://nettuts.com";s:3:"url";s:53:"http://envato.s3.amazonaws.com/rss_images/nettuts.jpg";s:5:"title";s:7:"NETTUTS";}s:9:"feed_type";s:3:"RSS";s:12:"feed_version";s:3:"2.0";s:8:"encoding";s:5:"UTF-8";s:16:"_source_encoding";s:0:"";s:5:"ERROR";s:0:"";s:7:"WARNING";s:0:"";s:19:"_CONTENT_CONSTRUCTS";a:6:{i:0;s:7:"content";i:1;s:7:"summary";i:2;s:4:"info";i:3;s:5:"title";i:4;s:7:"tagline";i:5;s:9:"copyright";}s:16:"_KNOWN_ENCODINGS";a:3:{i:0;s:5:"UTF-8";i:1;s:8:"US-ASCII";i:2;s:10:"ISO-8859-1";}s:5:"stack";a:0:{}s:9:"inchannel";b:0;s:6:"initem";b:0;s:9:"incontent";b:0;s:11:"intextinput";b:0;s:7:"inimage";b:0;s:17:"current_namespace";b:0;s:4:"etag";s:29:"gA4GWZwWC7tB+983UGDcz5FwFOU
";s:13:"last_modified";s:31:"Wed, 14 Nov 2012 18:50:09 GMT
";}