Skip navigation
Help

Web application frameworks

warning: Creating default object from empty value in /var/www/vhosts/sayforward.com/subdomains/recorder/httpdocs/modules/taxonomy/taxonomy.pages.inc on line 33.
Original author: 
(author unknown)

Great design is a product of care and attention applied to areas that matter, resulting in a useful, understandable, and hopefully beautiful user interface. But don’t be fooled into thinking that design is left only for designers.

There is a lot of design in code, and I don’t mean code that builds the user interface—I mean the design of code.

Well-designed code is much easier to maintain, optimize, and extend, making for more efficient developers. That means more focus and energy can be spent on building great things, which makes everyone happy—users, developers, and stakeholders.

There are three high-level, language-agnostic aspects to code design that are particularly important.

  1. System architecture—The basic layout of the codebase. Rules that govern how various components, such as models, views, and controllers, interact with each other.
  2. Maintainability—How well can the code be improved and extended?
  3. Reusability—How reusable are the application’s components? How easily can each implementation of a component be customized?

In looser languages, specifically JavaScript, it takes a bit of discipline to write well-designed code. The JavaScript environment is so forgiving that it’s easy to throw bits and pieces everywhere and still have things work. Establishing system architecture early (and sticking to it!) provides constraints to your codebase, ensuring consistency throughout.

One approach I’m fond of consists of a tried-and-true software design pattern, the module pattern, whose extensible structure lends itself to a solid system architecture and a maintainable codebase. I like building modules within a jQuery plugin, which makes for beautiful reusability, provides robust options, and exposes a well-crafted API.

Below, I’ll walk through how to craft your code into well-organized components that can be reused in projects to come.

The module pattern

There are a lot of design patterns out there, and equally as many resources on them. Addy Osmani wrote an amazing (free!) book on design patterns in JavaScript, which I highly recommend to developers of all levels.

The module pattern is a simple structural foundation that can help keep your code clean and organized. A “module” is just a standard object literal containing methods and properties, and that simplicity is the best thing about this pattern: even someone unfamiliar with traditional software design patterns would be able to look at the code and instantly understand how it works.

In applications that use this pattern, each component gets its own distinct module. For example, to build autocomplete functionality, you’d create a module for the textfield and a module for the results list. These two modules would work together, but the textfield code wouldn’t touch the results list code, and vice versa.

That decoupling of components is why the module pattern is great for building solid system architecture. Relationships within the application are well-defined; anything related to the textfield is managed by the textfield module, not strewn throughout the codebase—resulting in clear code.

Another benefit of module-based organization is that it is inherently maintainable. Modules can be improved and optimized independently without affecting any other part of the application.

I used the module pattern for the basic structure of jPanelMenu, the jQuery plugin I built for off-canvas menu systems. I’ll use that as an example to illustrate the process of building a module.

Building a module

To begin, I define three methods and a property that are used to manage the interactions of the menu system.

var jpm = {
    animated: true,
    openMenu: function( ) {
        …
        this.setMenuStyle( );
    },
    closeMenu: function( ) {
        …
        this.setMenuStyle( );
    },
    setMenuStyle: function( ) { … }
};

The idea is to break down code into the smallest, most reusable bits possible. I could have written just one toggleMenu( ) method, but creating distinct openMenu( ) and closeMenu( ) methods provides more control and reusability within the module.

Notice that calls to module methods and properties from within the module itself (such as the calls to setMenuStyle( )) are prefixed with the this keyword—that’s how modules access their own members.

That’s the basic structure of a module. You can continue to add methods and properties as needed, but it doesn’t get any more complex than that. After the structural foundations are in place, the reusability layer—options and an exposed API—can be built on top.

jQuery plugins

The third aspect of well-designed code is probably the most crucial: reusability. This section comes with a caveat. While there are obviously ways to build and implement reusable components in raw JavaScript (we’re about 90 percent of the way there with our module above), I prefer to build jQuery plugins for more complex things, for a few reasons.

Most importantly, it’s a form of unobtrusive communication. If you used jQuery to build a component, you should make that obvious to those implementing it. Building the component as a jQuery plugin is a great way to say that jQuery is required.

In addition, the implementation code will be consistent with the rest of the jQuery-based project code. That’s good for aesthetic reasons, but it also means (to an extent) that developers can predict how to interact with the plugin without too much research. Just one more way to build a better developer interface.

Before you begin building a jQuery plugin, ensure that the plugin does not conflict with other JavaScript libraries using the $ notation. That’s a lot simpler than it sounds—just wrap your plugin code like so:

(function($) {
    // jQuery plugin code here
})(jQuery);

Next, we set up our plugin and drop our previously built module code inside. A plugin is just a method defined on the jQuery ($) object.

(function($) {
    $.jPanelMenu = function( ) {
        var jpm = {
            animated: true,
            openMenu: function( ) {
                …
                this.setMenuStyle( );
            },
            closeMenu: function( ) {
                …
                this.setMenuStyle( );
            },
            setMenuStyle: function( ) { … }
        };
    };
})(jQuery);

All it takes to use the plugin is a call to the function you just created.

var jpm = $.jPanelMenu( );

Options

Options are essential to any truly reusable plugin because they allow for customizations to each implementation. Every project brings with it a slew of design styles, interaction types, and content structures. Customizable options help ensure that you can adapt the plugin to fit within those project constraints.

It’s best practice to provide good default values for your options. The easiest way to do that is to use jQuery’s $.extend( ) method, which accepts (at least) two arguments.

As the first argument of $.extend( ), define an object with all available options and their default values. As the second argument, pass through the passed-in options. This will merge the two objects, overriding the defaults with any passed-in options.

(function($) {
    $.jPanelMenu = function(options) {
        var jpm = {
            options: $.extend({
                'animated': true,
                'duration': 500,
                'direction': 'left'
            }, options),
            openMenu: function( ) {
                …
                this.setMenuStyle( );
            },
            closeMenu: function( ) {
                …
                this.setMenuStyle( );
            },
            setMenuStyle: function( ) { … }
        };
    };
})(jQuery);

Beyond providing good defaults, options become almost self-documenting—someone can look at the code and see all of the available options immediately.

Expose as many options as is feasible. The customization will help in future implementations, and flexibility never hurts.

API

Options are terrific ways to customize how a plugin works. An API, on the other hand, enables extensions to the plugin’s functionality by exposing methods and properties for the implementation code to take advantage of.

While it’s great to expose as much as possible through an API, the outside world shouldn’t have access to all internal methods and properties. Ideally, you should expose only the elements that will be used.

In our example, the exposed API should include calls to open and close the menu, but nothing else. The internal setMenuStyle( ) method runs when the menu opens and closes, but the public doesn’t need access to it.

To expose an API, return an object with any desired methods and properties at the end of the plugin code. You can even map returned methods and properties to those within the module code—this is where the beautiful organization of the module pattern really shines.

(function($) {
    $.jPanelMenu = function(options) {
        var jpm = {
            options: $.extend({
                'animated': true,
                'duration': 500,
                'direction': 'left'
            }, options),
            openMenu: function( ) {
                …
                this.setMenuStyle( );
            },
            closeMenu: function( ) {
                …
                this.setMenuStyle( );
            },
            setMenuStyle: function( ) { … }
        };

        return {
            open: jpm.openMenu,
            close: jpm.closeMenu,
            someComplexMethod: function( ) { … }
        };
    };
})(jQuery);

API methods and properties will be available through the object returned from the plugin initialization.

var jpm = $.jPanelMenu({
    duration: 1000,
    …
});
jpm.open( );

Polishing developer interfaces

With just a few simple constructs and guidelines, we’ve built ourselves a reusable, extensible plugin that will help make our lives easier. Like any part of what we do, experiment with this structure to see if it works for you, your team, and your workflow.

Whenever I find myself building something with a potential for reuse, I break it out into a module-based jQuery plugin. The best part about this approach is that it forces you to use—and test—the code you write. By using something as you build it, you’ll quickly identify strengths, discover shortcomings, and plan changes.

This process leads to battle-tested code ready for open-source contributions, or to be sold and distributed. I’ve released my (mostly) polished plugins as open-source projects on GitHub.

Even if you aren’t building something to be released in the wild, it’s still important to think about the design of your code. Your future self will thank you.

0
Your rating: None

Node.js employs an event-driven architecture and a non-blocking I/O model, and it provides some blindingly fast performance to some types of data-intensive Web apps. It is about JavaScript on the server side. LinkedIn, Yahoo and eBay are among ardent Node.js users, and none other than Microsoft has discussed end-to-end JavaScript coverage on its Azure cloud. The objective is absolutely fast I/O.

This article features Joyent CTO and co-founder Jason Hoffman, who discusses the roots and reason of node.js. He said:

“Why we did it is, at Joyent we have a lot of servers, more than most companies in the Fortune500 and we write in C, in a compiled language. We needed to write servers in a dynamic language for talking to certain protocols. Basically, we had to write service endpoints. The Node part of Node.js is separate. It is designed so that it can handle a lot endpoints – on the order of a million. Most things written for the [Java Virtual Machine] can only handle 20,000 [endpoints]. Node is meant to handle a lot of I/O. So we took the node part and married that with V8 [the JavaScript virtual machine from Google].”

0
Your rating: None

The .NET Framework exposes classes that allow you to programmatically access the C# language compiler. This might be useful if you want to write your own code-compiling utilities. This article provides sample code that enables you to compile code from a text source. The application allows you to either just build the executable or build the executable and run it. Any errors that occur during the compilation process are displayed on the form.

using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;

CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();

parameters.GenerateExecutable = false;
parameters.OutputAssembly = "AutoGen.dll";
CompilerResults results = icc.CompileAssemblyFromSource(parameters, yourCodeAsString);
0
Your rating: None

When CSS 3 is implemented, we will be able to create documents with multiple columns. Until then, we can use this filter to transform input such as
[multicolumn cols="2"]
one
two
three
four
five
[/multicolumn]

into two lists, side by side. The first will contain "one two three" and the second will contain "four five".

Note that list items are created based on line breaks in the input text. Do not insert <li> tags.

If you use the HTML filter after this one, make sure that it allows the tags that this filter produces.

Theming

The module defines two theme functions:

theme_multicolumn_list($list, $columns = 1)

Format one column.
theme_multicolumn_row($list)

Arrange columns side by side.

You can override these by defining functions MYTHEME_multicolumn_list() and MYTHEME_multicolumn_row() (replacing MYTHEME with the name of your theme) in your theme's template.php file.

The default implementation of theme_multicolumn_list() is simply a call to theme('item_list'). The default implementation of theme_multicolumn_row() includes a call to drupal_add_css(). If you write your own theme functions, and you know in advance how many columns you will be using, then you may prefer to add the CSS through your theme.

TODO

  • Allow the user to specify the type of list (ol, ul, maybe plain).
  • Allow the user to add a CSS class.
  • Use a preprocess function to convert <multicolumn> to [multicolumn].
0
Your rating: None

Product Review

Drupal 7 Module Development While I consider myself well-versed at the front-end theme aspects of Drupal, I had been wanting to delve a little deeper into its underpinnings, if only to understand how modules work. Deconstructed, Drupal is essentially a series of modules working together — be that “core,” the bare CMS — or “contrib,” third party modules available for download from drupal.org. So, in an effort to bolster my skill set, I recently read Drupal 7 Module Development, from Packt Publishing and found it to be an excellent resource.

If you have more than a passing interest in Drupal, then you are probably aware of the significance of such a talented group of developers collaborating on this book. The author list reads like a veritable who’s who in the subculture of Drupal…

Matt Butcher works for the New York Times Company on their ConsumerSearch site. Greg Dunlap works for NodeOne, an agency in Sweden. The rest of the authors are heavy hitters at Palantir, a development firm based in Chicago.

This book does not mince words, skipping past the whole installation process, because such information is readily available online anyway. What I like best about this book is that, after the requisite introductory chapter covering the broad strokes, it gets right into building a module from scratch, aptly named First, that outputs a list of all the currently installed modules. Chapter 2 also touches on code standards (covered here), as well as how to write automated unit tests.

Chapter 3 is all about theming, and not just at a superficial stylistic level, but also how to make use of powerful preprocess functions, that allow the theme layer to edit Drupal’s output before it reaches the browser. I have implemented such techniques to make my own site HTML5, rather than the default XHTML 1.0.

With module building and theming covered, chapter 4 jumps into how to theme a module, because modules themselves typically output a varying degree of markup themselves, and can (optionally) ship with CSS to handle any custom styling. Also covered is consideration for languages that read right to left, as internationalization has been a priority even since the earliest days of Drupal. Such cases should not be overlooked if you intend to make your module publicly available for reuse.

Chapter 5 draws back the curtain a bit, so to speak, venturing into the administrative interface. Some modules do not actually affect a site’s public look and feel at all, but instead are built to facilitate a content creation workflow and/or user management. This chapter covers how to write an admin module that makes use of Drupal’s email API, sending the user a warning message if he or she is deemed to be in violation of the site’s terms of service.

Chapters 6 and 7 cover how to work with custom content and field types, using artwork as an example of a special type of content (ch. 6), with the dimensions of each piece of artwork necessitating a custom field type (ch. 7). The authors are quick to point out that Drupal itself is versatile enough to handle such cases, without needing a custom module. However, they chose this as a faux case study, simply to explain building modules that handle custom content and fields.

Chapters 8 and 9 cover permissions and security, as well as node access. One thing I have always appreciated about the community of developers around Drupal is the dedicated security team. Chapters 8 takes the same mindset, that any anonymous site visitors could potentially be nefarious, and explains the best ways to ensure that you are not leaving your site vulnerable due to exploit vectors in your module. Additionally, chapter 9 talks about conditionally showing content to various user tiers, depending on if they have the necessary credentials to view it.

Chapter 10 is all about JavaScript, explaining that Drupal makes jQuery and jQuery UI available to you as a developer. For instance, via jQuery, Drupal automatically adds a draggable handle that makes any <textarea> resizable in all browsers, even those that don’t natively support it. When building your own modules, you can also tap into the convenience that jQuery affords. This chapter covers how to employ an Ajax approach to forms, rather than doing a full round trip to the server to refresh the entire page. It also touches on how to add translation via Drupal.t(), the JavaScript equivalent of Drupal’s PHP function t().

In chapter 11, working with files and images is explained. Whereas previous versions of Drupal required an additional module to be installed in order to manipulate images, as of Drupal 7, this functionality is built into core. As a module developer, you can tap into the native Image API, allowing users to manipulate graphics via a web interface. The authors explain the process of adding a watermark to a photo, as well as how to desaturate, rotate, and resize images.

You will love chapter 12 if you build a lot of Drupal powered sites, and find yourself repeatedly setting your preferred defaults each time. While not about module development, per se, it covers how to bundle modules and site configuration into what’s called an “install profile.” This allows you create a custom installation of Drupal, preconfigured with everything you would normally have to do anyway.

Basically, this book leaves no stone unturned. As if the aforementioned chapters weren’t already enough, at the end of the book, there are two appendices that cover databases and security, to be used more as a reference than a tutorial.

I would recommend Drupal 7 Module Development to anyone who has familiarity with building sites in Drupal, but wants to take their prowess to the next level. The collective expertise imparted in this book simply cannot be overstated.

0
Your rating: None


Angular: A Radically Different Way of Building AJAX Apps

Google Tech Talk July 28, 2010 ABSTRACT Presented by Misko Hevery. Angular teaches your old browser new tricks. It is what HTML would have been like, if it was designed for building web-applications. Angular is radical because it eliminates boilerplate code with declarative rather than imperative syntax. Angular: * Allows you to create custom HTML elements and attributes that provide dynamic behavior * Declaratively describe web-applications behavior with little JavaScript. * Creates an environment that provides trivially reusable widgets, data-binding, "automatic MVC", server resources, and other primitives useful in building AJAX apps. * Builds apps that have orders of magnitude less JavaScript than equivalent apps written in classical way. * Eliminates waiting on compiling for UI changes.
From:
GoogleTechTalks
Views:
1578

15
ratings
Time:
56:23
More in
Science & Technology

0
Your rating: None

Arrange Fields screenshot 1

This module lets you drag-and-drop the fields of any CCK content type into the positions you would like for editing. This makes it super simple to have forms with inline fields, which you can change at any point. Tab indexing is also updated, so no matter how you arrange the fields, the users can still tab through them easily.

Features

  • Drag and drop fields into any arrangement you want. Makes web-forms look more like pen-and-paper forms.
  • Resize textfields and textareas by dragging.
  • Edit CCK configurations for each field (required, help text, allowed values, etc) in a popup without having to leave the page.

read more

0
Your rating: None

Views Infinite Scroll provides a #586668: Pluggable pagers that enables views infinite scrolling ( autopaging, depaging, endless pages ...you name it) by using jquery.autopager plugin. using this module with views page display will load another page whenever the user reaches bottom of the page.

Requirements

Important notes

  • This module is not compatible with Views Ajax support.

Alternatives

  • http://drupal.org/project/views_infinite_pager
  • The module provides somehow similar features to Views Infinite Scroll, although, it overrides views mini pager's theme, preprocessing and ajax behavior. If you are not willing to upgrade to Views 3.x (though I really recommend doing so, the upgrade is seamless and Views 3 comes loaded with tons of new features :) ), then you can use this alternative module.

0
Your rating: None