Important Development Techniques New to Me

Generating MVC View Models from Arrays Generated by jQuery

Many times on my latest work-for-hire project I’ve been reluctantly adding a new MVC View Model to the build. I don’t want to be one of those developers slapping redundant clutter out of ignorance and the fear of being perceived of as “too slow.” And it is time consuming to write a View Model—especially for an HTML form with several dozen data points.

What makes me feel just a little bit better is the fact that a View Model needs to be redundant for these very powerful reasons:

  • The View Model often flattens hierarchical relationships on the server among several entities/tables. Remembering this literally puts the View back into View Model.
  • The View Model is a strongly-typed representation of what can be generalized into a big bag of name-value pairs. My assertion here is that it is easier to maintain the strongly-typed object than to painstakingly account for several dozen strings in a bag.

What’s even better for me is this little JavaScript utility function:

    $.rx.utilityGetInputProperties = function (selector, context) {
        var props = [];
        $(selector, context)
            .find('input, select, textarea')
            .each(function () {
                props.push($(this).attr('id'));
            });
        return _.sortBy(props, function (p) { return p; });
    };

This jQuery function will allow me to generate POCO C# View Model classes with properties named after the id attribute of HTML form elements quite quickly. There are several “peculiar” conventions from my little world here:

  • I am biased toward using AJAX/JSON to post HTML form data—this means I can use the id attribute of HTML form elements.
  • My IDs for HTML forms are in Pascal case—which can be quite annoying to JavaScript-centered developers. Worse, is me deliberately doing this for CSS class names as well!

Using $(document).ajaxComplete() as a Secondary Initialization ‘Hook’ for Client Scripts

Getting JavaScript loaded and running is ridiculously difficult. In very large, complex clients $(document).ready() is not enough. My intent as a programmer is to compose logic into discrete units that are as independent as possible. This makes maintaining the code easier and it allows new developers to not freak out with the fear of breaking something somewhere in the mysterious deep… Without something like $(document).ajaxComplete(), the level of independence would decrease—as I would be tempted to pack more and more dependencies into the $(document).ready() function block as the client got larger and larger. This is what my $(document).ajaxComplete() pattern looks like today:

    $(document).ajaxComplete(function (event, xhr, options) {
        if (options.url.indexOf('/MyMvcRoute') !== -1) {
                //Visuals for each panel:
                $.rx.panels();
                $.rx.panelOne();
                $.rx.panelTwo();
                $.rx.panelThree();
            });
        }
    });

Related Links

  • Underscore.js: “Underscore provides 60-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of forEach, map, reduce, filter, every, some and indexOf.”
  • HTML5 JSON Report format: tool to view any JSON data in a human-readable HTML
  • The Cicada Principle and Why It Matters to Web Designers
  • Clever use of HTML5” via @sambrown
  • HTML5 Shiv: “Sjoerd Visscher mentioned an interesting technique that could be used to force IE to use the specified CSS styling. Specifically, once you create a new DOM element (of the same name as the one in the document) all styling is applied. You don’t even have to inject the element in order for this to occur.”
  • Exploring Globalization with jQuery: “One file jQuery.glob.all.js includes around 350 cultures currently. So with this we need to include only this file for all the cultures supported by the plugin.”
  • jQuery 1.5 Released: “Easily the largest change in this release is the complete rewrite of the Ajax module in jQuery. This rewrite helps to fix a lot of gaps that existed in the old Ajax system along with providing a higher level of consistency across the API.”

jQuery Unknowns of the First Half of 2011

Not everyone can know everything about jQuery plugins—not even John Resig. What is ruthless about some IT managers, from my hopefully distant past, is their expectation that you, the developer, know everything about the task you are about to undertake. It took me way, way too long to find out that this expectation, conscious and subconscious, is really the garbage of reckless youth—no matter how old the IT manager appears to be.

What is a nightmare scenario is realizing this magical expectation not only includes knowing all about the technology but also how the technology can be abused (the anti-patterns and just the anti-). I formally introduced this realm of hell to myself in “What’s most busy about the IT consulting business…” A couple of months later I’m still looking for a way to study Microsoft-based anti-patterns based on real data collected in the .NET 3.5/4.x timeframe.

So I have more experience with managing technological unknowns. The technology of the day (today) is jQuery. This is the client technology that’s paying my bills these days—so it would behoove me (my mother used that word) to hoof it and trot over the traps that caught me in these early days of HTML 5.


NY Tech Summit 2010

Here in the 21st Century, Internet Explorer Still Objectively and Scientifically Sucks

Internet Explorer is a living monument of corporate politics. This is why it sucks. Someone is going to write a book and then consult for a documentary film about Internet Explorer. Where’s the filmmaking skills of Robert X. Cringely when you need ’em?

In the meantime, install Internet Explorer 9 (there’s tweet I heard that said don’t install the 64-bit version because the JavaScript engine is “5x slower”—it’s not using the Chakra Engine) and go to http://html5test.com. This brand-new, 21st-century, browser will score the lowest of all the “modern” browsers.

In my recent work, here’s what stands out about Internet Explorer:

  • It has the best Jscript debugging experience for any integrated development environment on the planet. In spite of this, I still use Firebug on Firefox and console.log() (yes, IE Developer Tools also supports console.log()—in a super-annoying way).
  • Internet Explorer 8 can’t do rounded corners (easily)—so Cornerz, yet another jQuery plugin, is still needed.
  • Internet Explorer 8 can’t do CSS drop shadows (easily).
  • I recommend using jQuery UI for designing any “pop-up” visual because Internet Explorer 8 has a very different interpretation of the offset of a block display. I lost hours of time and wasted my client’s money (as far as I’m concerned) discovering this “innovation” from Redmond.

File Input on an HTML Form for Cross-Browser Consistency is Ridiculously Hard

The fact that I did not know just how awful the situation is for <input type="file" /> betrays my lack of concern for providing ways of allowing “users” (interactors) to write files to a web server. Looks like I missed Web 2.0 entirely. (I did notice over the years how, say, flickr.com took exceedingly tedious steps to make file upload sexy—with much success.) In “CSS: Styling File Upload / Select Input Control <input type=”file” … />,” the situation is made explicit:

Let’s face it, the native implementations of file uploading control of HTML form is ugly, throughout most of the browsers, and not consistent at all.

Recent work led me to Sebastian Tschan, his work, jQuery-File-Upload. Like SlickGrid (see below) it’s on github.com and, like SlickGrid, it has little documentation—but, compared to the other stuff that’s out there, it’s awesome. It became awesome after these humps on the learning curve:

  • jQuery-File-Upload by default uses an entire form element to do its magic. I tried to use a special, documented ‘micro-format’ to allow other visuals in the form but this did not work for me.
  • As I’m new to jQuery-File-Upload I prefer $('#my-form').fileUpload() over $('#my-form').fileUploadUI(). The latter being more complicated and unrelated to my client’s specifications. I notice that there is more documentation and code samples for .fileUploadUI().
  • The documentation for the onLoad option strongly suggests that the handler object in the function signature for onLoad has a parseResponse function. I have yet to find this function… perhaps it’s in another satellite file?

Deciding to Use SlickGrid Means Working with Almost No Documentation

There are too many freaking grids for the jQuery universe and no one is willing to declare themselves the supreme master of this space. I’m waiting for that grid episode on DocTypeTV to bust a move on this technical matter.

Before recent work, before my telecommuting experiment, I got mired in the well-documented, monumentality of jqGrid. Now it’s SlickGrid. I can see why I would prefer jqGrid over SlickGrid during my days at Amgen:

  • jqGrid has better documentation than SlickGrid
  • SlickGrid requires jQuery UI, which can be seen as an extravagant dependency (see below) that I would be unable to defend before a team of developers totally ignorant of the existence of jQuery UI.

jQuery UI “Theme Roller” Means Dragging around a Bunch of Files

jQuery UI is a celebration of the image file—my “theme rolled” customization has about 13 image files. Most of these image files make the gradient effect that CSS 3 promises to eliminate. In spite of the impressive idea in the celebrated ThemeRoller application, I literally cringe and almost dread having to change my custom theme. The way you “save” your theme, for example, is with a super-long URL which, for me, fails to preserve every detail painstakingly specified (this URL is also saved in a CSS file in your download).

It is fascinating to me how I am unable to find other Blog posts criticizing ThemeRoller. Even the search term “ThemeRoller alternative” returns little or nothing. I refuse to accept that ThemeRoller is beyond serious improvement. I suspect that serious CSS people, building on some 960 grid system, don’t even use it.

Related Links

“HTML 5 Parsing” and other marked up links…

John Resig: “One of the biggest wins of the HTML 5 recommendation is a detailed specification outlining how parsing of HTML documents should work. For too many years browsers have simply tried to guess and copy what others were doing in hopes that their parser would work well enough to not cause too many problems with HTML markup found in the wild.”

“jQuery 1.5 RC 1 Released”

John Resig: “We want to encourage everyone from the community to try and get involved in contributing back to jQuery core. We’ve set up a full page of information dedicated towards becoming more involved with the team. The team is here and ready to help you help us!”

“PHP 5.3.5 and 5.2.17 Released!”

php.net: “The PHP development team would like to announce the immediate availability of PHP 5.3.5 and 5.2.17. This release resolves a critical issue, reported as PHP bug #53632 and CVE-2010-4645, where conversions from string to double might cause the PHP interpreter to hang on systems using x87 FPU registers. The problem is known to only affect x86 32-bit PHP processes, regardless of whether the system hosting PHP is 32-bit or 64-bit. You can test whether your system is affected by running this script from the command line. All users of PHP are strongly advised to update to these versions immediately.”

“Creating PHP Websites with WebMatrix”

Brian Swan: “As I read those posts (and others), I was left wondering about the extent of PHP support in WebMatrix (which is what I’ll look at in this post). As it turns out, PHP is fully supported, but it requires a little bit of work up front in this beta release of WebMatrix (a smoother experience for PHP developers is planned for the final release). If you want to work on any of the PHP applications that are available in the Web Application Gallery, the experience is very smooth—just follow Ruslan’s blog post. However, if you just want to see how WebMatrix works as a PHP IDE for building your own sites (and you don’t want to install one of the PHP apps in the app gallery), then here’s what to do…”

“jQuery Performance Tips And Tricks—A Free 30 Minute Talk”

Addy Osmani: “Hey guys. Today we’re going to take a look at best practices, tips and tricks for improving the performance of your jQuery code. Performance optimization is a crucial aspect of building ‘snappy’ client-side applications and something which all developers using jQuery should bare in mind.”

“Announcing HTML5 Labs”

Jim O’Neil: “As you hopefully know by now, despite the hype, HTML 5 is not a completed specification. In fact, back in 2008, the author of the specification, Ian Hickson, estimated HTML 5 wouldn’t be a Proposed Recommendation until 2022! Indeed, the W3C site shows there are still significant aspects of the HTML 5, CSS 3, DOM and other specifications being fleshed out – just take a look at the ‘warning’ in every W3C Working Draft: Implementors should be aware that this specification is not stable.”

“HTML Video Codec Support in Chrome”

Mike Jazayeri: “We expect even more rapid innovation in the web media platform in the coming year and are focusing our investments in those technologies that are developed and licensed based on open web principles. To that end, we are changing Chrome’s HTML5 <video> support to make it consistent with the codecs already supported by the open Chromium project. Specifically, we are supporting the WebM (VP8) and Theora video codecs, and will consider adding support for other high-quality open codecs in the future. Though H.264 plays an important role in video, as our goal is to enable open innovation, support for the codec will be removed and our resources directed towards completely open codec technologies.”

“Guide to Bing Query Language Published”

Bing.com: “Bing offers several ways to augment a basic Bing query. For the most part, we’ve talked about using the Bing API to tailor requests. However, there is another tool that you can use in either an API request or a Bing box: Advanced Query Language. We’ve just published an extensive list (with descriptions and examples) of the operators, or syntactical units, that comprise this language.”

“The Future of HTML 5”

Bruce Lawson video: “Full transcription available at joeloverton.com/html5. We’d like to say a HUGE thank you to @joeloverton for doing this transcription!”

“Modernizr”

“Have you ever wanted to do if-statements in your CSS for the availability of cool features like border-radius? Well, with Modernizr you can accomplish just that!”

My Picks from “45+ New jQuery Techniques For Good User Experience”

Buy this Book at Amazon.com!
Smashing Magazine:

AJAX Upload: “This AJAX file upload plug-in allows users to easily upload multiple files without having to refresh the page. In addition, you can use any element to trigger the file selection window. The plug-in creates a semi-transparent file input screen over the button you specify, so when a user clicks on the button, the normal file selection window is shown. After the user selects a file, the plug-in submits the form that contains the file input to an iFrame. So it isn’t true AJAX but provides the same user experience.”

jQuery AJAX Contact Form:Here is a quick and easy way to make a jQuery AJAX contact form with a “honeypot” to foil email bots, load success and error messages dynamically without leaving the page and provide descriptive error messages detailing why submitted values have failed validation.”

jQuery File Tree: “The jQuery File Tree is a configurable AJAX file-browser plug-in for jQuery. You can create a customized, fully-interactive file tree with as little as one line of JavaScript code.”

CSS Sprites2: “This tutorial demonstrates how to implement inline CSS Sprites2 using jQuery.”

Tablesorter:Tablesorter is a jQuery plug-in that turns a standard HTML table with <th> and <td> tags into a sortable table without the need for page refreshes. Tablesorter can successfully parse and sort many types of data, including linked data, in a cell.”

Over 800 Lines of jQuery Later…

Buy this Book at Amazon.com!I am not being sarcastic: with jQuery you do write less and do more. The ‘over 800 lines’ is less than what is needed for my YUI 2.x JavaScript base. Apart from the brilliant syntax, much of this reduction is due to the plug-in culture of jQuery. I’m sure jQuery veterans would ask, why would need even 800 lines? These are the generalities that I’m for:

  • $.rx.client extension functions to define how I organize the Client and define conventional ways of producing jQuery-UI-based alert and confirm messages. One format for alerts and one for confirmations is shared by the entire Client application. There is also a cute little helper function, $.rx.client.setKeydownTrigger() which wires keydown triggers of other events—usually click events. Respect goes out to Nadia Alramli for showing me how this is done in jQuery via StackOverflow.com.
  • $.rx.ajax extension functions to define how I attach an event to an AJAX call. The options object literal (a jQuery convention) can be configured to support a confirmation before an AJAX call. I sacrificed the terseness of the post() and get() methods for this flexibility. One notable convention is the conventional invocation of $.rx.client.displayBuilder.build() when the AJAX complete event fires. This conventional build() function uses the super-power of jQuery to—you guessed it—query the elements returned from the AJAX call to attach events and format.
  • $.rx.dateTime is not doing much right now. It has one extension function I use it to append the current time to date values from the Datepicker.
  • $.rx.validation extension functions of my legacy <form/> validation code that has been maintained for over a decade. This old stuff is still useful even in view of the Validation plugin by Jörn Zaefferer.

One very important thing I’ve learned about jQuery is that it is wrapper over DOM elements. Concealing DOM elements is not a design goal. You can have your old DOM elements back with $(selector).get(n) or $(selector)[n]. This means that my old code can still work.

Another important bit is the jQuery.extend() function. It took me way too long to see its importance in “name-spacing”:

$.extend({rx:{}}); //$.rx
                  
$.extend($.rx, {client:{}}); //$.rx.client
                  

I use the term extension function for jQuery procedures that are not chaining the jQuery object. You don’t need a selector query to get these helpers. The term extension method refers to procedures in the jQuery chain.