Web Development – Disadvantages of Unobtrusive Script Patterns

design-patternshtml5javascriptweb-development

First of all, is there a name for this as a bona-fide design pattern? Currently I've just been referring to it as "unobtrusive javascript". Here is a brief example of what I am talking about:

1.) Use HTML5 data-* attributes to define values that will be used in UX scripts. Something like this:

<input type="date" data-app-calendar="datepicker" />

2.) Use script to initialize the javscript behaviors using these data attributes

(function($) {
    $.app = $.app || {};
    $.app.obtruders = $.app.obtruders || {};
    $.app.obtrude = function(selector) {
        var obtruder, obtruders = $.app.obtruders;
        for (obtruder in obtruders) {
            if (!obtruders.hasOwnProperty(obtruder)) continue;
            if (typeof obtruders[obtruder] === 'function')
                obtruders[obtruder].apply(this, 
                    Array.prototype.slice.call(arguments, 0, 1) || document);
        }
    };

    $.extend($.app.obtruders, {
        calendar: function (selector) {
            $(selector).find('[data-app-calendar=datepicker]').datepicker();
        }
    });

    $(function () {
        $.app.obtrude(document);
    });

})(jQuery);

What you end up with, imo, is presentation markup that is very cleanly separated from behavioral scripts. The above example is simple, but you can extend it to more complex scriptable UX like google maps (I am working on this right now). You can even add new "obtruders" in separate javascript files by extending the $.app.obtruders object literal.

Before we start using this pattern more widely in our app, I wanted to pick brains for opinions and try to get ideas of some potential disadvantages of an approach like this. What do you like about this pattern? What don't you like? Why would you choose not to use it?

Best Answer

It's a common pattern, "unobtrusive javascript" is a widespread name for it, and it's generally considered superior the alternatives (putting JavaScript calls directly into links and event handlers).

The only disadvantage that I can think of is that it makes the behaviour harder to discover. When looking at the HTML, you have no idea what the dynamic behaviour is or even where it's defined. This can be mitigated by conventions or IDE support.

Related Topic