Writing Modular JavaScript: New Premium Tutorial
plusvideos

Writing Modular JavaScript: New Premium Tutorial

Tutorial Details
  • Topic: Modular JavaScript
  • Availability: Premium Exclusive
  • Format: Written and Video
Download Source Files

When writing an entire web application in JavaScript, it’s very important to have well-organized code; maintaining a spaghetti-coded project will only cause you headaches and nightmares. In this tutorial, I’ll show you how to modularize your code to make it easier to manage large JavaScript projects.

Become a Premium member to read this tutorial, as well as hundreds of other advanced tutorials and screencasts.


Quick Preview

Get the Flash Player to see this player.


Join Net Premium

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of Tuts+ sites runs a premium membership service. For $19 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, Vectortuts+, and CgTuts+ For the price of a pizza, you’ll learn from some of the best minds in the business. Become a Premium member to read this tutorial, as well as hundreds of other advanced tutorials and screencasts.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Ashish

    NIce,

    I wiil read it when i will reach home.

  • Leigh Kaszick

    Certainly looks like you put a lot of effort into this tutorial.. It’s a shame I cancelled my premium subscription :S

  • http://twitter.com/vijaydev_ Vijay Dev

    Precious knowledge sealed off in closed doors.

    Knowledge is only multiplied when shared – some wise guys said this a long ago.

    P.S: This comment is for the author. I totally respect envato.com.

  • http://www.moltee.com/ Reece

    Very Nice, When I buy a premium account do I get access across all the tuts plus sites?

    • http://andrewburgess.ca Andrew Burgess
      Author

      Yes, you’ll get access to the premium tuts on all the Tuts+ sites that offer them.

  • http://gauravjassal.com Gaurav

    Hello Andrew, You mentioned almost 2 and a half hours screencast with the tutorial. I download the source (400KB). Can you tell me where is the screencast. Thanks G

    • http://andrewburgess.ca Andrew Burgess
      Author

      Did you buy it on the Tuts+ Marketplace? If so, re-download the tutorial zip file from your downloads dashboard; it’s been updated to include the screencast.

      • http://www.nunomedia.com Nuno

        It does not include the screencast yet. Is possible to watch from the Tuts+ panel. But I want to download and watch it later.

      • http://andrewburgess.ca Andrew Burgess
        Author

        hmm, where exactly is the screencast not included? I’ve just checked now on both the Tuts+ Marketplace and the Net Premium Members Panel, and I can download the screencast from both places. Can you try again?

  • http://www.cms-spletnih-strani-gostovanje.si Gostovanje spletnih strani

    Very nice, I think I buy a premium account.

  • http://www.helloeverything.co.uk David

    Looks like a good article.

  • http://whatupderek.com Derek

    Great tutorial. Definitely compliments Zakas’ talk.

    I have a question that falls in to the “personal style” realm, but wanted your opinion.
    Would you write ajax functionality in a specific module or would you write a separate ajax-module that listens to the other’s event?

    For instance in the shopping cart example; if you wanted to persist the cart’s state to a database would you have a shopping-cart-persist module that listens to when the shopping cart is updated and then save the data?

    • http://andrewburgess.ca Andrew Burgess
      Author

      I think it would be best to include that in the shopping-cart module, because it is behaviour of the shopping cart. That would be one use for the cartItems variable: when we add an item to the cart, send the updated contents of that variable to the server.

      If you wanted to put that in a separate module, I wouldn’t have a special shopping-cart-persist module; I’d use a simple persist module; then, notify something like this:

      {
          type : 'data-persist',
          data : { destination : 'page.php', data : cartItems
      }
      

      That way, you could use the persist module would be very multi-purpose.

      However, I think I’d prefer to put the persist code right in the shopping cart module; the only reason I’m put it in its own module would be if I found myself using that functionality repeatedly.

  • Andrew Wayne

    Great tut as always Andrew! :)
    wish u could expand the Storing Data with JSON tut (Part 2 perhaps?) and more on Mustache library quick tip..
    More JSON tuts! lol

    • Christof Haemmerle

      hi andrew.

      +1 would love to see a JSON part 2 tut

  • http://www.winservers.co.in anuj

    hey thanks mate :)

  • http://fredjou.unblog.fr/ Jean

    Good article, thanks :)

    it should implements drag and drop ;)

  • Kevin

    I think your Sandbox.ignore() method is not really needed.

    You can simply add an extra line to the Core.stop() method:

    stop : function(moduleId) {
    var mod = moduleData[moduleId];
    if (mod && mod.instance) {
    mod.instance.destroy();
    mod.events = null; // add this line and your events will be deleted for that module
    mod.instance = null;
    } else {
    this.log(1, ‘Stop Module “‘+ moduleId +’” : FAILED: module does not exist or has not been started’);
    }
    }

    • Kevin

      Even better would be delete mod.events;

      Just like you did in the Core.removeEvents() method.

  • DED

    Andrew, very nicely done. I think you demonstrated a reasonable approach to Zakas’s theory. There are two things I would like to note regarding your tutorial though.
    1. You obviously planned your application very well, and that planning informed your decisions about the architecture of your code. It would be helpful to many learners to get a glimpse of that planning stage, especially if you talked about what you thought about in making decisions. For instance when creating modules you knew about methods that you would later put in the core and sandbox. What steps did you take to get the code structured out. Did you make a diagram, did you actually code functionality first and then abstract ( refactor) that out into the code structure? Those would be helpful to know, it’s what education folks call meta-cognitive steps and teaching those helps learners transfer what they learn to new situations. So, then we could an idea about the complete process of this approach an apply to our own custom apps.
    2. You mentioned that a con of this approach is that it is difficult to get your head around: I think that might actually be a plus. It means that the logic is tight but doesn’t express itself verbosely. If you ever studied algorithms you see the same thing when trying to understand some complex ideas. It’s hard to understand but once you get it, it makes a lot of sense.

    • http://andrewburgess.ca Andrew Burgess
      Author

      Thanks! Great points; about the first, I didn’t do any kind of diagramming or much else at all when planning the sandbox. When I originally did this project, I just started coding the modules and “made up” the functions I saw the sandbox would need as I went along. The main difference in what I originally did and what you saw here is that after writing the four modules originally, I looked at the list of sandbox functions and weeded it out a bit. For example, I had both a find(selector) method and a find_in(parent, selector) method. It wasn’t until after I had written the modules that I decided to only give modules access to DOM element within their “domain” and realize that when that was the case, find_in wasn’t necessary. So there wasn’t very much pre-planning; if was mainly a “stand back and assess the work”-type thing after I had written the modules.

      On point two: I completely agree. However, tight logic does seem to make the barrier to entry a bit higher.

  • MrShish

    Great Tutorial.
    Do you have any links for further reading regarding this. Pretty powerful stuff.
    A bit hard to comprehend thou.

  • http://whatupderek.com Derek

    I am having trouble finding the bit about naming events. What is the rule of thumb for naming them? For instance if I want to toggle the visibility of a module/widget I wouldn’t within that widget look for a “toggle-visibility-of-widget” event. Especially when 99% of the time it will most likely be a standard click event.

  • Kevin Turner

    Nice deep-dive on JavaScript modularization, Andrew! It definitely compliments Zakas’ presentation.

    Regards,
    Kevin (Mississauga, Ontario)

  • Kratos

    Hi Andrew,

    very good tut. I have to buy it immediately.
    But one question. Is it possible to init modules with dynamic DOM elements?

    Regards,
    Andre

  • Kevin Turner

    How do I handle key events using this technique?

    For example, I have a page with a textbox and I want to to submit the page when the user hits the enter key. The module needs to know which key was pressed.

    In my module’s init() method I have this:

    sb.addEvent(guess, ‘keyup’, this.handleProcessGuess);

    But the handleProcessGuess() does not receive the usual evt parameter, which it needs in order to check if the enter key was pressed (e.g. if(evt.keyCode === 13)).

    • Kevin Turner

      Disregard that last comment I added.. I was just missing the evt parm in my method declaration. Doh!

  • Barry

    Why are all my post being deleted?

  • Lehnhard

    This premiumtutorial is the reason why i am now a premiummember of tutsplus.

    So first its really a great tutorial and i learned a lot by this. But i have some questions.

    The diffrent modules communicate over named signals with each other. This work fine. But all modules are on the Page from the beginning. We never destroy them. We write code for that but never use it. So is it for example possible to give the items we put in the shoppingcart a functionality with a dynamic creation of a core-Module (each item has a functionality which is described by a module and listen only fpr signals for this item)? Or think we have for some reason diffrent productpanels, which we can load over ajax from the server and we want for each of them a searchbar and a filterbar. Can we create this dynamicly? Is ther somewhere an example for stuff like this?

  • Jorn

    Hi Andrew, hope you’re still following this ;)

    In your example a module is always 1:1 with a DOM element.
    Now suppose you have two DOM elements (for instance two search fields that search trough a long list of messages).
    I would like each search field to have their own instance of a module, but that’s not possible with this approach.

    How would you solve this situation?

    • Jorn

      Btw, great addition ;)

  • Jack

    Does this tut makes sense now? I guess its better to move to frameworks such as Backbone?