Home    Files

software times™  Files...

January 9, 2012

Pragmatic JavaScripting


pragmatic
adjective
dealing with things sensibly and realistically in a way that is based on practical rather than theoretical considerations: a pragmatic approach to programing JavaScript.
For a long time I avoided JavaScript as much as possible because it is simply daunting, it's huge, it's Object Oriented with hundreds of JavaScript Objects (or so it seems) each with a variety of Methods and Properties. Keeping it all in your head, which could be done with earlier, simpler languages, is just not practical, if it were even possible. Even that master archiver, Google, is not all that useful if you don't know what you are looking for. Searching for JavaScript solutions on the web can easily turn into a needle in the haystack game.

zebra striping
To sumarize the problem, in OOP you have to manipulate Objects which can only be done by using the Object's Methods and Properties. The practical solution is to document the Object you are working with, on the fly, when and where you need it -- without leaving JavaScript -- without resorting to external references. The good news is that this is easy to do!

A typical JavaScript problem I had some difficulty in solving was scrolling a particular row into view. The page has a table inside a scrolling div. When the page loads, the preselected row should become visible. The solution is to scroll the div. What Method should be used? This is where "instant documentation" comes in handy. You want a list of the Object's Methods and Properties. The following inspectObject(a) function will give you all the information you need, maybe more that you need!

function inspectObject(a) {

    var output = 'Object: '+a+'\r\r';
    for (property in a) {
      output += property + ': ' + a[property]+'; ';
    }
    alert(output);
    
}
The particular Object I wanted to scroll into view was document.getElementsByName(row)[0] and I had a look it it with:

    inspectObject(document.getElementsByName(row)[0]);
The output from inspectObject() displays in an Alert which is fine for small objects. With large objects a lot of the info is below the fold and not visible. I copy the text from the Alert box into my favorite text editor (BBEdit) and there I can use all the editor's facilities to help in my searches. In the above case, I searched for "scroll" and quickly discovered a Method that seemed promising: scrollIntoView(). It was!

Denny Schlesinger



Home    Files
Top
Copyright © Software Times, 2000, 2001, 2003. All rights reserved
Last updated March 8, 2009.