Alex Sexton

Web Hacking. JavaScript.

What I Learned About the Google Chrome Store

| Comments

While traveling in Europe this week, I had the pleasure of going to a Google Chrome developer event put on by Mike Mahemoff (The Moff™) and Paul Kinlan (whom Paul Irish says is a genius, so that’s a good start). I took some notes during the meeting. I didn’t know tooo much about the chrome app store, so I figured I’d post what I learned in a very digestible manner for anyone who’s googling for the right keywords next week.

A bulleted list of things I learned at the meetup (other than how strong The Moff™ is in real life):

  • Here were some slides for the night: http://3.ly/y2dd

  • No date on the official release of the store but apparently “Coming soon”

  • There will be a free and a pay model, but the pay model is only launching in the US (then other markets to follow)

  • There will be a way to do billing monthly/yearly/onetime (paypal (“harder”, not sure of the specifics)/googlecheckout)

  • There will be an API to see if the user really bought something

  • 5% of your revenue is theirs, rest is yours (yay) (way better than 30% – wowy)

  • Apps aren’t chrome specific. They say they’d love to make stuff work cross browser, but they are going a little bit different direction from W3C widget spec…

  • Pay to install

  • You install apps directly into the browser

  • There will be a user-permission popup for (location, notifications, storage, etc)

  • Open now… I guess this means you can build stuff that works as a chrome app already (but there’s no store)

————————-Second Half—————————–

  • Apps different than websites (even though theyre both web)

  • You CAN use flash/silverlight/java if you want, but they don’t auto install, so if the user doesn’t have them, you’re SOL

  • Google hosted (if you want)

  • If you go Google hosted, they are packaged (let’s get a spec for this going!), if not, just a URL and a manifest

I stopped taking notes at this point to actually build a chrome app. It was insanely easy, so I’m happy about that. Yay chrome apps. I’d love to see how these pan out. I don’t think it can work until they are cross-browser, etc, but half the fun of them is that if it’s a chrome app, it doesn’t have to work in FF, so you can use specific APIs… so it’s a tradeoff.

Aiight. Tried to keep that as informal as possible. Hope someone wanted this info!

Alex

On “Rolling Your Own” Large jQuery Apps

| Comments

As a preface, make sure you’ve read my super-smart and talented yayQuery co-host Rebecca Murphey’s blog post on this topic

here: On jQuery Large Applications and here: On Rolling Your Own.

Rebecca points out some huge holes in the jQuery-verse when it comes to large-application development, and gives her opinion on why she doesn’t think jQuery is ever a good fit for a large application. I disagree, and she’s successfully convinced me to write a post on why I think what I do, so here we are.

Also, please, no one point out that I prefer Django over Pylons, which is essentially the same argument :D . The difference, though, is that I think Pylons is awesome, and that people should totally be using it for large applications on the backend, as long as they prefer it!

First, I will start by mentioning that I have written several large applications using jQuery, and that I think that from a ‘framework’ perspective, something like Dojo (which Rebecca supports) or YUI3 serves as a much better core to a large application than jQuery. However, arguing that ‘you shouldn’t use jQuery in your large application’ is an entirely different topic. jQuery does not describe or prevent any framework of application development, so you are free to choose your own to suit your needs. I do not advocate the incorrect use of jQuery as the core of your application. I do advocate JavaScript at the core of your application, though.

jQuery is a tool (lolz)

I build large applications that use jQuery. I don’t build large applications on top of jQuery. This incredibly important distinction hasn’t been very well clarified thus far in the conversation. I think it’s a fair ambiguity, however, because while it’s possible to use jQuery in well-structured ways, it’s certainly the road less travelled. The ‘common jquery user’ tends to throw everything onto the jQuery namespace, and pull in everything as plugins, and generally very tightly couple their applications to jQuery. I think the distinction is still important for the argument, because it doesn’t rule out the fact that you can write some really nice applications using jQuery.

It’s not jQuery, it’s you.

I think the thought that people are incapable of using jQuery in this manner stems from quite a few bad consulting experiences with companies using jQuery for no reason other than the fact that it’s the cool thing to do, but using it entirely in an entirely backwards manner. This is also not a good way of making library decisions (at least in the long term). It doesn’t reflect poorly on the code in jQuery so much as it reflects poorly on either the messaging from the jQuery team, or just the general population’s inability to write good code and tendency to do what’s popular. However, if Dojo were the hip-cool-designer library, they would suffer from the exact same problem.

Any library, in the hands of people who don’t know what they’re doing (even FuseJS), will not serve the needs of the application. This is a reality for anything that becomes popular. It’s easy to like Dojo for the quality of code that comes out of it, but that’s because the significantly less amount of people who use it are really good JavaScript Developers. That’s important.

Being a good JavaScript developer before you start writing your application is the key to building good large applications. It’s not what library you use. This is why I write about inheritance in JavaScript for the majority of my large jQuery apps articles. It’s the JS people need to learn. In fact, I’d imagine there’d be some insanely backwards code from people using Dojo who didn’t know what they were doing. You have to remain level-headed, though, and try to evaluate the tools without bringing in your past experiences with other developers. You can certainly choose Dojo to get away from jQuery noobs, but recommending Dojo to jQuery noobs is just bringing your problem along with you.

Roll it.

Aiight, with all that out of the way (yikes), let me give my most objective reasoning possible for why I think it’s ok to use jQuery in a large app. Please keep in mind that I’m not advocating against Dojo or YUI3, I’m advocating against the absolute notion that ‘jQuery should never be used for large applications.’ Use what you prefer, of course.

Rebecca’s core argument against rolling your own jQuery large app is that 1) no one else knows your code-base, so supporting is harder, and 2) the solutions in a library like Dojo are built to work together by smart people who have thought long and hard about the problems, and rolling your own are more fragile and can cause issues with upgrade paths and compatibility, etc. These are valid points, but I think they are painted with a narrow frame of reference for the type of app structure you might use in a large jQuery app.

It’s common knowledge that a separation of concerns is key to any large application. Loose-coupling is something that I’ve blogged extensively about in the past. If you have a problem updating a portion of your application, it’s because you wrote it too coupled. This is not unique to jQuery. Dojo’s API stays about as backwards-compatible as they come (seriously), but that doesn’t mean your old code will just work. In fact one of the few experiences I’ve had with DojoX code is that some of the less popular DojoX modules often need changes to return the correct values, or not throw errors. The core of the library, has been significantly more impressive in regards to this, but we’re talking about code that you write, not the library core.  I am a fan of Dojo’s backwards compatibility efforts over jQuery’s. Changing an API in a point release isn’t always the most friendly change for devs.

Her list of requirements for a large app is well considered. It is a comprehensive list of things that often come in handy when building a large application. All of these things have been answered by smart people, in the JavaScript community. Much like her example with templating, you can decide which pieces to use (except, directly, not with library specific code…). Instead of overriding Dojo.templated you just change out the contents of your template rendering function with the new one. If you correctly loosely-coupled your application, then ‘yay’, you switched out a part of your app in less lines of code!

Here’s the list of things that she’d expect from a framework, along with the appropriate solutions I’d consider:

  • DOM manipulation tools - jQuery core
  • Ajax tools - jQuery core
  • A dependency management and build system - RequireJS
  • Clear patterns for code organization, such as namespaced modules - The module pattern and a few object literals
  • An inheritance system, preferably one that offers multiple inheritance, for sharing code across modules and staying DRY - modules +$.extend
  • A non-DOM-centric, loosely coupled API for communication between modules - pub/sub || custom events
  • A widget system that makes use of the inheritance system, with lifecycle management (setup/teardown) and templating - $.fn + mustache/microtemplates
  • A system for maintaining templates separate from JavaScript while interning them into the build to eliminate HTTP requests - <script “text/html”> + text!requirejsdependency
  • A system for abstracting RESTful server communication - assumes you want REST - but $.ajax usually works anyways…
  • For a UI-intensive project, a rich widget system pluggable to arbitrary data sources and designed with an easily-extended API - jQuery UI or ExtJS on jQuery
  • For an enterprise project, a11y and i18n provisions, as well as clear patterns for file organization - jQuery UI has many of these, you can also build them in. Require dictates some directory structure.

These requests are pretty obviously skewed to someone who likes working in Dojo. They are all pretty awesome ways to do things, but to say that you needed the module pattern is to entirely overlook other very valid ways of structuring complex code. Of course Dojo offers ways to do things like event-oriented programming over object-oriented. The point here is that, if Dojo has answered every question, and jQuery and friends has also answered every question (perhaps not in the same place), it’s going to be just as hard to pick up the code base and figure out what’s going on. I could structure my Dojo app in a way that Rebecca doesn’t like, and use template overrides for template-languages that she despises, and I could tightly couple my dom elements and their attributes to my data, and it’d all be in beautiful Dojo. That Dojo has answered all the questions does not facilitate that you understood those answers or that you agree with them.

The positives

I somewhat reject the notion that using jQuery, Underscore, Require, Mustache, and the module pattern (as facilitated by Require) is “rolling your own.” Sure you piece them together, by choosing how you use them, but you do the exact same thing when you choose how you use the various parts of Dojo. I think that all of these tools are as strong as the Dojo alternatives. You can argue that you could use any of these tools with Dojo because it’s so flexible that you can put anything in, but then you can’t argue that ‘rolling your own’ is bad, because that’s what you just did. Either use Dojo, or agree that sometimes, it’s not that bad to pull in a different way of thinking, you can’t have it both ways.

jQuery normalizes things across browsers when you need it to, and serves as a mostly-fantastic way of doing dom-manip and ajax. If you use it according to it’s strengths, you still can choose some really strong software alongside it that was specifically designed to be awesome at what it does.

Underscore gives you a very solid utility library, much like you’d find in Dojo, and it’s extensible to boot. You can use it in two of the major paradigms natively, and it falls back to native implementations when it can. It’s hardly fragile, and it’s insanely easy to integrate into your project. It’s no worse or better than Dojo’s offering.

RequireJS is likely going to be used in Dojo 2.0 and James Burke, who wrote Require, also wrote most of the Dojo dependency management system. Require incorporates all the sweet stuff from Dojo, plus some really awesome future stuff coming from the CommonJS peeps. Some apps, though, don’t require a ton of dependency management. Single page apps are likely not going to be terribly dependency heavy, and if you want… you can leave out the dependency management system all-together, and still use your modules, just like you always wanted. You can switch it out for LabJS if you want speed too.

Templating was the example that Rebecca used to show that she could roll her own templating style in Dojo. She used mustache instead of the default Dojo offering. I can’t argue against that. I’m in favor of pulling together the correct tools for the job.

A lot of what is nice about Dojo, is it’s prescribed format for creating modules. There’s quite a bit of flexibility, but anyone who could understand the way that Dojo does this could easily understand some of the basic underlying patterns that it’s enhancing. I can use object.create and the module pattern to my hearts content to structure my app, and that’s not some ‘wild tangent’ that no one will ever be able to unravel. It’s a simple, and common pattern that you’d be required to understand to use the Dojo method. Sure there’s no prescribed way to exactly structure this, but that’s the case with the ‘extremely flexible’ Dojo offering as well.

I’m not advocating creating super complex alternatives to Dojo’s module structure. I think JavaScript offers a simple and flexible interface to creating and manipulating objects. I can choose which ever way I’d like. The module pattern is 2 pages of of text and code examples in The Good Parts. Just go read that.

TL;DR

Dojo is a fantastic library that I would encourage you to pick up and add to your skillset. jQuery can be a fantastic tool to use as well. “Rolling Your Own” application with good tools alongside jQuery is no harder to understand than a Dojo app, nor is it harder to support, and it’s likely more specific to your needs. The fragile part of your code isn’t in the tools you use, it’s in the code that you write around them.

I wish we’d focus less on whether jQuery or LibX was a good or bad choice for large applications, and focus on the fact that people who don’t know JavaScript are never going to write well-structured apps. Anyone who does understand the fundamental concepts behind JavaScript would be able to do it well with or without Dojo. Your language should provide your structure, and your toolkits should dictate your tools on top of that structure.

Learn JavaScript first. Then care about large apps. Then make a smart decision, according to your preferences, on which, if any, library you want to use.

-Slex

TXJS and ScriptJunkie

| Comments

I have been pretty neglectful of my blog since I started at Bazaarvoice, but I think I’m going to try to pick up a little bit. That being said, here’s a short update.

I am now a featured author on ScriptJunkie – a new website from Microsoft about front end development. Check out my post “Building and Maintaining Large JavaScript Applications”

I’ll likely cover a few more topics concerning large application structure in the future, both on my blog and on yayQuery and ScriptJunkie.

Also, TXJS happened. I’d suggest going to the totally awesome webpage and catching the slides and the speakerrate pages for all the talks to get caught up on how much awesomeness happened. Also, my fridge is still full of left over beer, so if you’re in town… beer.js at my place.

Using Inheritance Patterns to Organize Large jQuery Applications

| Comments

Last will and testament - lolz I want to introduce/reinforce a pattern for developing large applications with jQuery. I did not invent any of this, but I find that the resources that describe this technique are few and far-between.– so I’m taking a shot at it.

By and large, when using jQuery, developers seem to forget the paradigms they learned for well structured code in other languages. This is likely due to the fact that jQuery is effectively neutral when it comes to your structural methodology or inheritance patterns, and therefore doesn’t push someone in any one direction. Many times in other libraries (See Dojo Declare/Provide/Require, or MooTools Class, etc.), a paradigm is used and exclusively offered, and then code generally ends up more uniform than the oh-so-common-massive-jquery-indented-chains that I’m sure you’ve seen .

I’m not going to necessarily suggest that you use any single inheritance pattern, as there are many options, and each makes sense for different people and different situations. I do however suggest that you know your options. There are a few good reads on the topic of Inheritance in javascript, and I would strongly suggest people read at least a bit of the following:

Choosing your form of modularity is an important step. If you come from a background of highly-classical inheritance (I learned Java in school, so…I know that world) then perhaps starting with a classical implementation is going to be your best choice. If you are trying to stay slim and do the things a little more in the “JavaScript way” (a term that means essentially nothing), then you might try to use prototypal inheritance. For my examples, any form of inheritance will at least work on most accounts.

I’ll jump straight to a code example of this technique in use, and then describe it’s setup and structure:

1
2
<!-- Just an empty div to begin with -->
<div id="mySpeaker"></div>

Then we’ll run our javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(function(){
  // Call a custom plugin for your object on a dom element
  $('#mySpeaker').speaker({'name': 'Alex'});

  // Have quick access to the actual speaker object
  var mySpeaker = $('#mySpeaker').data('speaker');

  // The interface of the object that you build can
  // wrap more complex dom manipulations that are
  // separated from actual program logic.
  mySpeaker.speak('I am a speaker.'); // Results in a dom update

  // This shows automatic access to correct element in the dom
});

And the html now looks more like this:

1
2
3
4
<div id="mySpeaker">
  <h1>Alex</h1>
  <p>I am a speaker.</p>
</div>

The key here is that we didn’t have to call something like $elem.append(‘Alex’) nor did we even have to consider what would happen when a speaker object was called with the speak() function. I consider this to be the key to modular development. This level of abstraction helps keep the how and the what separated (or “loosely coupled” – if you like buzzwords). The other thing that was important to note is that after we instantiate the plugin, we have a clear two-way path between our Object and our Dom Element – both have an easy way to immediately access the other. This is important, because we often have different points of entry to jump-start a routine, so being able to access the part that you need quickly and easily is important.

Implementing this technique is pretty simple, and should actually take less brain power to set up than traversing through the dom in your head to figure out a crazy chain.

Let’s start with the Speaker object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Object Speaker
 * An object representing a person who speaks.
 */
var Speaker = {
  init: function(options, elem) {
    // Mix in the passed in options with the default options
    this.options = $.extend({},this.options,options);

    // Save the element reference, both as a jQuery
    // reference and a normal reference
    this.elem  = elem;
    this.$elem = $(elem);

    // Build the dom initial structure
    this._build();

    // return this so we can chain/use the bridge with less code.
    return this;
  },
  options: {
    name: "No name"
  },
  _build: function(){
    this.$elem.html('<h1>'+this.options.name+'</h1>');
  },
  speak: function(msg){
    // You have direct access to the associated and cached jQuery element
    this.$elem.append('<p>'+msg+'</p>');
  }
};

I use an object literal here which puts me in the Prototypal Inheritance camp, I believe, but this is just an easily digestible pattern.

As you can see, there are easy-to-read, small functions, that have a clear purpose. In our use of this pattern, we call api type methods like speak() but not necessarily an internal method (like _build). You can hide your internal functions either by naming convention (not really hiding them), or by using something like the module pattern. In our simple example, I have just added an underscore to the beginning of the function to indicate that it’s private.

Code that is organized like this is much easier to test and to change/read. This also allows you to change the way things function without changing the way that the Object api is used. For instance, we could change the speak method to alert the string instead of append it to the related element. We would have to change the internals of the speak function, but we could keep our call to it the same.

The bridge that we build is probably the most interesting part of this pattern. It’s a different approach than many of the popular plugins take (slightly different than jquery ui), but it has a few really great benefits.

The most simple way to do this is by hand:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Make sure Object.create is available in the browser (for our prototypal inheritance)
// Courtesy of Papa Crockford
// Note this is not entirely equal to native Object.create, but compatible with our use-case
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {} // optionally move this outside the declaration and into a closure if you need more speed.
        F.prototype = o;
        return new F();
    };
}
(function($){
  // Start a plugin
  $.fn.speaker = function(options) {
    // Don't act on absent elements -via Paul Irish's advice
    if ( this.length ) {
      return this.each(function(){
        // Create a new speaker object via the Prototypal Object.create
        var mySpeaker = Object.create(Speaker);

        // Run the initialization function of the speaker
        mySpeaker.init(options, this); // `this` refers to the element

        // Save the instance of the speaker object in the element's data store
        $.data(this, 'speaker', mySpeaker);
      };
    }
  };
})(jQuery);

And that’s it!

Now you have separated the creation of the plugin from the actual code itself. You are using the plugin to attach objects (with any inheritance patten) to dom elements and visa versa, but the plugin itself is just the connection and initialization code. This means that we could generalize this process further. I first saw this from Scott Gonzalez (of the jQuery UI team) and his code later became the ‘widget factory’ in jQuery UI. I prefer to not pass strings into my plugins in order to call functions, but it’s a valid approach as some people would take issue with having to pull out the object each time they started with a dom element.

Here is some code that might get you started writing/using a ‘bridge’ function (bridge is what’s found now in jQuery UI 1.8) that can help you attach your general code with a given plugin (since writing that same initialization plugin code multiple times would get old and defeat the whole DRY principle that our inheritance model has hopefully provided). This code is mostly courtesy of Scott Gonzalez because I couldn’t think of a more stripped down elegant approach to this. I changed it to accept Objects instead of Constructor Functions because that works a little better with my example (prototypal inheritance). I also force it to call my init function in order to save myself an extra call. (This example shows Scott’s use of this method along with John Resig’s Simple-Inheritance implementation – also very cool.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$.plugin = function(name, object) {
  $.fn[name] = function(options) {
                // optionally, you could test if options was a string
                // and use it to call a method name on the plugin instance.
      return this.each(function() {
          if ( ! $.data(this, name) ) {
              $.data(this, name, Object.create(object).init(options, this));
          }
      });
  };
};

// With the Speaker object, we could essentially do this:
$.plugin('speaker', Speaker);

// At this point we could do the following
$('#myDiv').speaker({name: "Alex"});

That’s about all there is to it. I’d encourage you to pick some pattern for your development that isn’t just inline chaining of jQuery function calls. This way of breaking up and organizing functionality in your code serves as a quick and easy jumping-off point for testing and modularity. It’s much easier to test the individual functions of a modular object than it is to write tests for a single-line chain of jQuery calls.

Also, I do get some feedback along the lines of “well, my code is not a plugin” – “this isn’t applicable to my code” – but I usually tend to disagree. The stigma that a jQuery plugin has to be for general consumption is flawed. I encourage you to use the plugin architecture if you are creating functionality based on a dom element selection. For instance, if you are adding an error notification system, it would be very easy to create a notification object that attaches to a div and has the methods required for notification directly attached to it, rather than having a function that merely hides and shows random dom elements.

I am doing a round up of performance on a lot of this inheritance usage and I should get to writing another entry on that soon, but from my early tests, using reasonable inheritance is generally not that expensive. If you are pushing the limits of CPUs and browser rendering, you might have to make some sacrifices, but for the general case, the instantiation hit of inherited objects is probably well worth your while.

I’d love to hear about the way you approach this problem.