Skip to main content

Mobomo webinars-now on demand! | learn more.

javascript

One of the most utilized, but not fully understood features of JavaScript is that, with a couple of exceptions, everything that you interact within the language behaves like an object.

This functionality can be seen most easily with Arrays and Functions. For example, the simple primitive version of Array (var arr = [1,2,3] for example) has object methods that can be used:

var arr = [1, 2, 3]; arr.indexOf(2); // >> 1 

Can I Use This Anywhere?

Before we get much further, let’s cover the things that aren’t objects. Simple primitives (boolean values (true and false), undefined, numbers, and strings) and null (which is it’s own type) are not objects. Numbers, Strings, and Booleans can act like objects, in that they have methods, but these types are immutable. True objects are changeable (mutable), and their properties are a collection key/value pairs, expressed as {key: value}, or accessed through dot or array notation: key.value or key[‘value’].

Here is an example of how Strings are not objects, but they are object-like:

var twoCities = "It was the best of times, it was the worst of times" twoCities.split(','); // >> ["It was the best of times", "it was the worst of times"]  // You can't add properties to Strings, but it acts like it's stored twoCities._author = "Charles Dickens"; // >> "Charles Dickens" twoCities._author // >> undefined 

This last case is important, because that aspect of mutable objects is what enables things like very simple caching on functions that perform complex tasks:

function renderTemplate (path) {   if (!renderTemplate.templates) {     renderTemplates.templates = {};   }    if (renderTemplate.templates[path] != null) {     return renderTemplate.templates[path];   }   var template = openAndReadFile(path);   return renderTemplate.templates[path] = template; } 

Because Functions are Objects, we can do this. If we wanted to do something similar with Strings, we cannot (and really, there’s not much need for it).

Leveraging Object-like Behavior to Your Advantage

Let’s walk through our caching example in more detail to see how it helps us run more efficient code.

The renderTemplate Function

Here we have a function named renderTemplate, which returns an HTML fragment that’s read from a file stored on the file system. Since we’re not focusing on how that’s done, but rather on how Functions being Objects is helpful, we are delegating the heavy lifting to a different method named openAndReadFile which handles the actual finding and opening of files. However, reading a file can be expensive and potentially redundant work, especially if you’re looping through a large list of items that all use the same template.

Here’s the function again, for reference:

function renderTemplate (path) {   if (!renderTemplate.templates) {     renderTemplates.templates = {};   }    if (renderTemplate.templates[path] != null) {     return renderTemplate.templates[path];   }   var template = openAndReadFile(path);   return renderTemplate.templates[path] = template; } 

The first two lines, if (!renderTemplate.templates) { renderTemplates.templates = {}; } put this “everything is object-like” concept right in the forefront. First, the function is checking to see if it has a property named templates (note that you can reference named functions from within themselves, which is what we’re doing here). If that property doesn’t exist, it creates it, and stores an empty Object primitive as the initial value.

The function then checks the templates Object to see if there’s a reference to the template stored in the cache, and returns it if it’s there. Then, if the template isn’t stored in the cache, the openAndReadFile function is called and then simultaneously stored in the cache and returned to the context from which it was called.

Actually, Everything isn’t an Object

This is a common misconception. JavaScript has six primary types: string, number, boolean, null, undefined, and object. Arrays and Functions are actually a variant of object, with Array being a sorted Object (and with it’s own sub-set of rules) and Function a callable Object.

Further Reading

This is a topic that’s been covered in greater depth by other authors, and I highly recommend that you check out the following (and not just for this specific topic, either!)

Categories
Author

Trying to get up to speed with D3 can be a daunting task. A quick google search will reveal hundreds of different starting points, almost all of which involve writing great swaths of code in order to build even the most basic of charts. Don't believe me? Here's the official example for a basic line chart. D3's biggest barrier to entry is its biggest strength - the flexibility that it provides to create nearly any sort of visualization that you can imagine.

In order to help foster good practices (by creating re-usable charts) and to give back to a community that is so willing to share its knowledge, Intridea has released a library that will help you get started much more easily: the D3 Fakebook. With just a few lines of code, you can easily render that same bar chart:

// From the D3 Basic Line Chart example: http://bl.ocks.org/mbostock/3883245 d3.tsv('examples/data/aapl_stock.tsv', function(error, data) {   var chart = new D3Fakebook.TimeScaleLineChart('#singleLine', {     data : data,     valueName : 'close'   });   chart.render(); }); 

Basic line chart

Easy as pie.

Getting Started

There are a few ways you can start using this library today: the first is that you can install it using bower ($ bower install d3-fakebook), which will pull down the dependencies (underscore.js and d3). You can also grab the files directly - there are both compiled JavaScript files as well as CoffeeScript.

Once you have the files loaded in your browser, you can access the different chart types under the D3Fakebook namespace. Each chart type takes a set of options that allows you to configure.

Wait - "Fakebook"? What’s up with the name?

The concept of a "fakebook" comes from Jazz - back in the 1950's, popular Jazz songs (also known as standards) were often compiled in to collections of books. Each song's transcription would have chord changes and the main melody would be written out, but not the whole song, since the musicians would make each their own by improvising on top of the chord changes.

Our goal with the D3 Fakebook is to do precisely that - give you a starting point to make amazing, beautiful visualizations that are purely your own. The Fakebook gives you a starting point and some guidance, but doesn’t force you to follow any specifically set path.

Follow the Changes

This is a living library, something we're using in our own projects (check it out in action on http://humanprogress.org) and though it's a bit rudimentary right now, we'll be adding more charts in the near future. If you want to help out, or if you've found a bug, feel free to submit a pull request on Github, and we'll incorporate it as soon as possible!

A few more roadmap items: we intend to add AMD support, compiled JavaScript modules (in addition to making the existing CoffeeScript files into actual modules), and nicer transitions.
Keep the conversation going! We'd love to hear from you!

Categories
Author

modevgov

Alright, so your big data infrastructure is up and running. You've collected and analyzed gigabytes, terabytes, maybe even petabytes of data and now you'd like to visualize that data on your desktops, tablets, and smart phones.

How do you go about doing this? Well, at a high level, big data when summarized/aggregated, simply becomes smaller data. The balancing act though is effectively displaying your data while also creating an ideal user experience.

In today’s talk, we’ll discuss the art and science of responsive web app development with HTML5, D3, CoffeeScript/JavaScript, Rails and MongoDB. Based on Intridea’s work with American Bible Society, we’ll show you how to visualize big data on mobile phones and tablets via the hosting site Amazon EC2 and processed using Amazon Elastic Map/Reduce with Apache Hive and Pig. In addition, we’ll showcase the beautiful dashboard developed by our UX team and discuss the architecture, both frontend and backend, behind this exciting project.

Visualizing Big Data on Small Devices will be @ 4 PM today in the Artisphere ballroom. Don't miss out!

Geeking out on big data? Check out the posts below!

  • Big Data, Small Budget
  • Single Page Apps: Popular Client Side MVC Frameworks
  • The Art of Humanizing Big Data
  • Categories
    Author

    In part one of our single page apps series, we discuss the top client side MVC frameworks rankings based on Github stats. Based on the number of people who starred the Github repositories, we can extract the following list of top JavaScript client side MVC frameworks:

    JavaScript MVC Framework Rankings

    link to the ranking app screen shot

    Notice if we count the Backbone extension frameworks like Marionette(4261), Chaplin(2483), and Thorax(1098), Backbone is still #1. Angular is growing at a faster pace though, and at some point may surpass the Backbone+extensions.

    Here's a little app using Rails 4, Twitter Bootstrap, Highcharts, and MongoDB/Mongoid to track the rankings of those frameworks. See screen shot below.

    link to the ranking app screen shot

    If you're interested, feel free to clone the repo https://github.com/tomz/jsmvc_rankings and play with it. You can run rake tasks to initialize and fetch latest stats, via github, by running the following:

    rake seed_stats  rake update_stats 

    The rake task can be set up as a daily cron job to collect the trending data of each framework, you can do so by running:

    whenever -w 

    Note: The term MVC is used loosely here to include all the MV* frameworks.

    In part 2 of this series, we'll walk through building a Single Page App, or SPA, using Backbone Marionette, Angular, and Ember.

    Resource Links:

    JS Framework tracking app https://github.com/tomz/jsmvc_rankings

    Angular https://github.com/angular/angular.js
    Backbone https://github.com/jashkenas/backbone
    Ember https://github.com/emberjs/ember.js
    Flight https://github.com/flightjs/flight
    Knockout https://github.com/knockout/knockout
    Marionette https://github.com/marionettejs/backbone.marionette
    React https://github.com/facebook/react
    Polymer https://github.com/polymer/polymer
    Spine https://github.com/spine/spine
    Chaplin https://github.com/chaplinjs/chaplin
    Sammy https://github.com/quirkey/sammy
    Enyo https://github.com/enyojs/enyo
    Thorax https://github.com/walmartlabs/thorax

    TodoMVC http://todomvc.com/

    Categories
    Author

    Recently, I was looking for a way to do a task N times in JavaScript (like Ruby's N.times method), which I found (_.times) in the Underscore.js library. This discovery exposed me to an alternate way to call the Underscore methods, using its chaining syntax.

    If you do a lot of work with Backbone, this syntax will be familiar. In Backbone, you can call many of the Underscore methods on models and collections:

    bookCollection.each( function(model) {   console.log( model.get('name') ); }); // >> 'American Gods' // >> 'Anansai Boys' // >> 'Coraline' 

    But what might not be obvious is that if you want to iterate over an object with Underscore, you can do the following:

    _(["American Gods", "Anansi Boys", "Coraline"]).each( function(book) {   console.log(book); }); // >> 'American Gods' // >> 'Anansai Boys' // >> 'Coraline' 

    Which is the same as doing this:

    _.each(["American Gods", "Anansi Boys", "Coraline"], function(book) {   console.log(book); } // >> 'American Gods' // >> 'Anansai Boys' // >> 'Coraline' 

    This becomes beneficial if you're working on a Backbone project and have a non-Backbone object that you want to iterate over. Going from collection.each(function(){}) to _.each(objs, function(){}) can be jarring, while _(objs).each(function(){}) is less confusing due to its similiarity.

    Ready to build an industry-changing product?

    Let's talk about your project today >>

    Categories
    Author

    Background

    As a Rails developer I normally spend most of my time on backend development, implementing features and functionalities. I am really confident about my Rails skills for backend work but rarely have I felt any happiness doing frontend work before. But things have changed since working on the new responsive intridea.com. I started some interesting frontend work from this project and fell in love with many UI skills and JS tricks, especially Pjax which I want to talk more about in this post.

    What is Pjax?

    Pjax is such a fantastic tool. I love this formula which describes Pjax well: pushState + Ajax = Pjax. When you need to store your page state in URL as permanent links, Ajax cannot do it gracefully. Thus, Pjax is a good choice to only update specific parts of web page and allow you to generate permanent links at the same time. Personally, I also like to call Pjax Perfect Ajax.

    Pjax Magic in Rails 3.2

    Let me show you how we use Pjax to speed up page loading for the current intridea.com website. Firstly, we use a rack middleware rack_pjax which will simply filter the page to respond to pjax-requests accordingly. Ok, add the gem to Gemfile as first step:

     gem 'rack_pjax' 

    Secondly, we should include this rack application into our Rails stack. This is easy too, just add this line in your config/application.rb file to config the middleware:

     config.middleware.use Rack::Pjax 

    Thirdly, we install the Pjax jquery plugin to assets/javascripts folder. You can download the Pjax source from this link. As with any other javascript plugin, be sure to include the file in application’s JavaScript manifest file as below:

     //= require jquery  //= require jquery_ujs  //= require chosen.jquery.min  //= require jquery.pjax  //= .... other js libs 

    OK, by doing the above three steps of installation and configuration we now have Pjax plugged into our application. It's time to enable the Pjax RULE for our current website. Basically, we want to add a 'data-pjax-container'-attribute to the container in which the HTML content will be updated by the Pjax response. The Pjax data container can be put in any layout or view file in our Rails application. That sounds cool, right? In our case, we only place a Pjax data container in layout as below:

     
    

    Wait, it's not finished yet. Now we enable the Pjax magic for the application. We enabled all links as "Pjax" triggers as below for example:

     $(document).ready(function() {    $('a').pjax('[data-pjax-container]', {timeout: 3000});  }); 

    It means, every link on the web page will trigger a Pjax request to the server, then the Pjax data container part will be updated by the Pjax response. Here we set timeout as 3000ms; you can set it higher if you use a custom error handler. Besides timeout, there are a bunch of other options for a Pjax function; they are almost the same as jQuery's $.ajax(), but there are still some additional options, you can take a detailed look at Pjax's doc.

    Attentions

    We have some javascript code which are binding to some Dom elements in that Pjax data container. For instance, we want to validate our contact form via Javascript, but a Pjax based page reloading will prevent the Javascript validator from working. That's because we only initialize the validator when Document is ready, but a Pjax reloading will not reload the whole document, which means we have to recall the validator again after the Pjax is done. Yeah, Pjax indeed fires two basic events while doing Pjax on your data container: pjax:start and pjax:end. To solve the above javascript validation issue, we need to call that function in Pjax:end callback as well.

     $(document).ready(function() {    var ApplicationJS = com.intridea.ApplicationJS;     $('a').pjax('[data-pjax-container]', {timeout: 8000});    ApplicationJS.validate_contact_form('#contact_form');     $(document).on('pjax:end', function(){      ApplicationJS.validate_contact_form('#contact_form');    });  }); 

    Similarly, if you want to add a loading indicator upon Pjaxing, then you might need to do something like this:

       $(document).on('pjax:start', function(){       // this will show an indicator on the <li> tag in navigation.       ApplicationJS.navSpinner('nav li.active');    }); 

    Finally, notice that Pjax only works with browsers that support the history.pushState API. Here is a table to show you all related information about popular browsers. When Pjax is not supported in some browser, $('a').pjax('[data-pjax-container]' calls will do nothing but work as normal links. So don't worry about any regarding mess ups.

    Have fun playing with Pjax, and please share your feedback and your own use cases with us on Twitter!

    Resources

    Categories
    Author

    Last Friday I decided to celebrate _whyday by taking a departure from my normal open source path and writing some Javascript (well, technically Coffeescript). So today we're announcing Sketch.js, a simple jQuery library to enable HTML5 Canvas "sketchpads" for any web application.

    Quick and Easy Doodling

    Sketch.js allows you to initialize a canvas element as a sketchpad as well as draw with different colors, stroke sizes, and tools (currently only a marker and an eraser). These tools can be accessed programatically or using special links with data attributes. Here's a basic example:

    <canvas id='mysketch' width='400' height='300'></canvas>  <script type='text/javascript'>   $('#mysketch').sketch(); </script> 

    That's all there is to it! The canvas will now be drawable by your users and, thanks to a relatively straightforward API, you can customize it to your heart's content.

    The HTML5 Canvas element is extremely powerful but it can be a bit daunting to get started. I took this as an opportuntiy both to learn it some myself and to provide a drop-in tool for others. Hopefully you find it useful!

    Learning on Whyday

    I set out on Whyday with the intent of learning a few new tricks. Here's some new things I tried out:

    1. Sketch.js is coded in Coffeescript. I had used Coffeescript before but never its class system or more advanced features. I like it!
    2. It's documented using Docco which has been one of the most straightforward and pleasant documentation experiences I've ever had. It also, as an annotated source engine, encourages clean source code.
    3. I set up an awesome instant build environment that uses Guard to compile Coffeescript, generate docs with Docco, and minify the JS into a build directory. The workflow worked really well.
    4. I tried to do a very little bit of unit testing using QUnit, which was my first major foray into Javascript testing. Unfortunately, with how much I was learning about Canvas at the same time, I didn't keep at the testing as much as I would have liked.

    All in all it was a great chance to sharpen my skills on something that I hadn't had a ton of experience with. You can see the docs (and live examples) on its GitHub pages or visit the code on GitHub. Enjoy!

    Categories
    Author

    Do you know Chris Selmer? He’s one of the Senior Partners here at Intridea. He’s also a person that likes to run, even when nothing is chasing him. Its baffling, I know. Although, I guess I’m no better, as I’ve recently started going to the gym and picking things up just to put them down. Not my best decision. Regardless, Chris likes to run. Thanks to this little tidbit I was granted the fortune of attending Ruby Nation this month when Chris, who had already purchased a ticket to the conference, decided to sign up for a marathon to run an only-acceptable-while-in-a-car distance that very same weekend. Good for him, and good for me.

    So what does this have to do with anything?

    Well, it was at that conference that some things came together for me. By things, I mean some thoughts that had been lounging around in the back of my head for quite some time. I always knew they were there, but I hadn’t given them any attention. Until Ruby Nation that is. There were a handful of sessions that really brought these thoughts to the forefront.

    The first session that caught my attention was our own Jerry Cheung’s presentation on Node.js (slides) where he gave a brief tour of Node and went over a handful of example scenarios where Node would work well alongside Rails. Then there was a Blake Mizerany's keynote in which he talked about being a polyglot, (someone who uses many languages). There was Chris Williams’ pirate-themed adventure called, “The Javascript Renaissance”. And finally, Ryan McGeary’s lightning talk on CoffeeScript (slides).

    In addition to the conference, there were a number of things floating around the Twitterverse that also got my attention. There’s been an increasing trend of tweets either denouncing jQuery-only JS developers and/or their practices OR tweets praising some new JS tool/library. Another enticing find was a link to the talented Rebecca Murphey’s keynote presentation called, “The jQuery Divide”.

    I’m guessing you’re probably starting to notice a theme here. It was the culmination of all these events that resulted this epiphany:

    “Shit, I’m one of those jQuery-only jackasses. I need to do something about it.”

    I tell myself that I write JS every day, but I don’t. I write jQuery. Don’t get me wrong, it gets the job done. But it never feels right. Now, jQuery and its DOM-centric approach (at least in common usage) aren’t all to blame. Its just as much my fault in that beyond the library, I know very little about the language. I intend to do something about it. I have a plan and I’m going to share it with you. First, here are my goals:

    • Gain a more thorough and detailed understanding of the JS language itself
    • Increase my exposure to the plethora of kick-ass new JS tools and libraries

    Here’s how I plan to do it. First, with two books that have come highly recommended:

    • Javascript: The Good Parts by Douglas Crockford - I’ve had this for a while and read about half-way through it, but at the time I just wasn’t interested enough to finish it.
    • Javascript Patterns by Stoyan Stefanov

    The second part of my plan is to spend a non-trivial amount of time with each of these:

    • Dojo - This seems to be the toolkit of choice when you want to move away from heavy DOM-dependency
    • Backbone.js - I like the idea of models and views on the front end.
    • Node.js - Having become so wrapped up in the Rails world, I’m interested in playing with a different web framework, or in this case, http parser.
    • Coffeescript - I know, I know. Its an abstraction from JS, but whatever. It's new and people seem to really like it or hate it (see the recent Rails 3.1 controversy) so it must be worth checking out.

    So that's my plan. With some poking and prodding from our Community Manager, Renae Bair, I’ll eventually post one or more follow-ups on what I’ve learned and my general thoughts on the experience.

    Categories
    Author

    If you've upgraded to the recently released jQuery 1.5 you may have heard about the fancy new AJAX facilities that allow you to define things like this:

    var jax = $.ajax({   url: '/some/url' })  jax.success(function() {   alert("It worked!");") });

    Well, that new power is known as Deferreds and it can be useful in more places than straight-up AJAX callbacks. If you want an in-depth look at the Deferred API you can look at the jQuery Documentation or read this very in-depth look at the API. But we're here today to take a look at a few practical examples that will let you really get the most out of the new functionality.

    A More Expressive setTimeout

    I've always hated the Javascript API for setTimeout. In my opinion it just doesn't make sense to have the duration come after the function. Using Deferreds, we can write a very English-friendly syntax for timeouts.

    $.wait = function(time) {   return $.Deferred(function(dfd) {     setTimeout(dfd.resolve, time);   }); }

    Now, thanks to the Deferreds, I can write timeouts in my app like this:

    $.wait(5000).then(function() {   alert("Hello from the future!"); });

    This is just a small example, but it shows you how easy it is to write deferred functionality into your applications. For our next trick, let's get a little more complex.

    Pretty Little Wrapper

    A common thing I find myself doing in jQuery is writing a small wrapper for an API. I always hate how messy the callback code gets, let's see if we can clean it up a bit using Deferreds.

    Twitter = {   search:function(query) {     var dfr = $.Deferred();     $.ajax({      url:"http://search.twitter.com/search.json",      data:{q:query},      dataType:'jsonp',      success:dfr.resolve     });     return dfr.promise();   } }

    Now I can easily perform Twitter searches in my app like so:

    Twitter.search('intridea').then(function(data) {   alert(data.results[0].text); });

    The Advantages of Deferreds

    Why would I want to use deferreds instead of standard callbacks? Well, for one, you can attach multiple callbacks to a deferred, giving you lots of flexibility in designing your application. Another way they're superior is by giving you built-in error handling. If you had a deferment that failed, you would be able to handle that as well:

    function doSomething(arg) {   var dfr = $.Deferred();   setTimeout(function() {     dfr.reject("Sorry, something went wrong.");   });   return dfr; }  doSomething("uh oh").done(function() {   alert("Won't happen, we're erroring here!"); }).fail(function(message) {   alert(message) });

    Deferreds are just a simple and powerful tool for you to use to make your code cleaner, more readable, and more functional. This is really just scratching the surface, so if you have any other fun Deferred tricks, I'd love to see them in the comments!

    Update: From the comments, I see that it is appropriate to return dfd.promise() instead of the deferred object itself. The code has been updated to reflect as much.

    Categories
    Author

    The Node Knockout is this weekend right now and I've been trying to teach myself Node and get ready in a variety of ways. One of the most important (and least clear) aspects of preparation was figuring out how to properly vendor the latest Node libraries for use in Heroku. I've got NPM up and running locally, but as of its latest release it has no built-in support for vendoring. Here's how I managed.

    Updated Method

    Since this post, the maintainers of NPM have released an updated version with a new command: bundle. Here's how to use it (make sure you have NPM >= 0.1.27 for this to work).

    First, create a package.json file in your project's root directory, and populate it with dependencies like so:

    {   "name":"yourproject",   "version":"0.0.1",   "dependencies":{     "express":"1.0.0rc2",     "ejs":""   } }

    If you don't need a specific version, just specify a blank string. Now that you've created a package.json, you need to run bundle:

    npm bundle ./vendor 

    This will bundle the dependencies specified into the vendor directory of your project. Now you're almost done! The last step is to add the vendor directory to your load paths:

    require.paths.unshift('./vendor') 

    That's it! You can now require the dependencies you've specified like you would if NPM were installed normally (i.e. without special functions or directory specifiers). Happy Node-ing!

    Old Method

    Warning: I am not an experienced Node developer and I may be doing this completely wrong. However, I am happy to publish this anyway with the hope that more learned Javascripters will correct my naive ways.

    NPM's Command Options

    NPM provides a few helpful command options that let you specify the directory of installation when you install a library. By using the --root and --binroot options you can use a folder inside your local project instead of the default NPM root. For example, in my project I created a vendor folder and then, to install Express, specified:

    npm install express --binroot ./vendor --root ./vendor 

    Now while this seems like it might do exactly what we want, it's not quite perfect. Rather than install everything in vendor, it installs the important stuff in vendor/.npm/.cache. This isn't the end of the world but can make for some pretty ugly require statements.

    The Require Blues

    So now you've got your packages all nice and installed inside your project directory (probably a lot of support files that you don't need, as well, but the Node slugs on Heroku tend to be small anyway so no biggie). Now you need to include them in your application. To do this, I wrote a quick function, vrequire that adds the necessary load path and then requires the library all at once:

    vrequire = function(lib) {    require.paths.unshift("vendor/.npm/" + lib + "/active/package/lib");   return require(lib);  }

    Now if I call vrequire("express") it will load up from my vendored library. If I deploy my app to Heroku, it's able to find everything it needs and (cross your fingers) launch and work correctly!

    Hopefully some people find this little guide useful, and I look forward to someone pointing me to the "real" way to do this stuff! If you want to poke around the exploratory code I've been creating to play with Node, you can find it on GitHub (but don't expect much!).

    Categories
    Author
    Subscribe to Javascript