This site is archived.

Rock solid JavaScript (or how to remove maintainer repellent)

Code & Development

Presenter:

Track

Code & Development

Experience

Intermediate

Focus

Developer

Rock solid JavaScript (or how to remove maintainer repellent)

45 minutes (+15 minutes Q&A)

Room:

tags

This session will include live, enlightening demonstrations that will help you write JavaScript code that is more beautiful and more maintainable. This session will help you understand and avoid some of the common pitfalls made possible by JavaScript's flexibility.

JavaScript code can be at least as beautiful as PHP code. Take a quick look at this PHP code:


function setText(&$elements, $text) {
  myeach($elements, create_function('&$element, $text',
    '$element = preg_replace("/>[^<]*</", ">$text<", $element);'),
    $text);
}

Probably most of you would agree with me this code is not ideal, yet even as you pick this apart, you can probably think of some JavaScript code in Drupal core and contributed modules that have exactly the same attributes that make this PHP code unattractive. For example:

Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.attach)) {
       this.attach(context, settings);
    }
  });
};

This second sample comes directly from Drupal core. Drupal JavaScript code uses this pattern everywhere.

For those that don't know by now, JavaScript is actually a difficult language. It has flexibility and features that allow you to do really interesting things. When coupled with jQuery, there is an undeniable inertia toward an implementation style that is unacceptable in other contexts. This is more than a curiosity. These development practices can be dangerous because while the developer can get the code to work very quickly, the code is not self documenting or obvious, often less efficient, and requires a higher degree of language sophistication on the part of the people maintaining the code than is otherwise necessary.

This session aims to help you understand more about the JavaScript language so you can identify the pitfalls of this coding style. I will demonstrate alternatives that will make your JavaScript code easier to maintain.

Topics:

  • What constitutes beautiful code, and how you can achieve that with JavaScript
  • JavaScript variable scope, closures, and memory leaks
  • Temporal code is unnecessary and makes it impossible to write self documenting code
  • Tools for JavaScript development (no, I'm not talking about Firebug)

Resources