Reality is a perception. Perceptions are not always based on facts, and are strongly influenced by illusions. Inquisitiveness is hence indispensable

Friday, July 18, 2008

Some java script snippets - Using Event Handler - part 2

Earlier we saw how to define a cross browser compatible event handler, we will see how to use it. Three different styles are demonstrated

Note: Copy the code into notepad or someother custom editor for more legibility




/**************************************************************************
Sample Event Listener definition begins
**************************************************************************/

var Handles = function(){

var test1 = function (aEvent){
alert(1);
}
var test2;
return {
test1: test1,
test2: test2
}
}
Handles.prototype.test2 = function test2(aEvent){
alert(2);
}
var HANDLES = new Handles();
/**************************************************************************
Event Listener definition ends
**************************************************************************/

function init(){
cleanup();
/* Three different ways to register functions,
the event Type and function's name are parameters */
// test1 is defined in HANDLES
HANDLER.registerEventHandlerWithType("load", "HANDLES.test1");
// test2 is added as prototype later on
HANDLER.registerEventHandlerWithType("load", "Handles.prototype.test2");
// cleanup is a globally visible function
HANDLER.registerEventHandlerWithType("unload", "cleanup");
}

function cleanup() {
/* Three different ways to unregister functions */
HANDLER.unregisterEventHandlerWithType("load", "HANDLES.test1");
HANDLER.unregisterEventHandlerWithType("load", "Handles.prototype.test2");
HANDLER.unregisterEventHandlerWithType("unload", "cleanup");
}



The html code for the above contains



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!--
Document : test2
Created on : 03-Jul-2008, 11:24:42
-->

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript" src="../js/File1.js">
</script>
<script type="text/javascript" src="../js/File2.js">
</script>
<script type="text/javascript" >
init();
</script>
</head>
<body onload="observeEvent(event)" onresize="observeEvent(event)">
<div>
Me
</div>
</body>
</html>

Some java script snippets - Event Handler - part 1

This is the first part of a sample event handler. We will see the declaration here

Note: Copy the code into notepad or someother custom editor for more legibility



var HANDLER = new EventHandler();
/**************************************************************************
Event Handler definition begins
**************************************************************************/
/* Cross browser event handler, that allows multiple handlers to handle the event */
function EventHandler () {
/* This is an array of eventHandler arrays, essentially a hashMap
defined using associative arrays.
Example content at run time would be
events["onload"] = ["adjustDiv", "centerAlignText"...];
where righthand side is a array of event Handling functions
*/
var eHandler = this;
eHandler.events = [];

function getHandlersForEventType(aEventType) {
/* if this is the first time we are listening the event,
create handlers array
*/
if(eHandler.events[aEventType]==undefined) {
eHandler.events[aEventType] = [];
}
return eHandler.events[aEventType];
}

function detectEvent(event) {
// grab the event object (IE uses a global event object)
event = event || ((this.ownerDocument || this.document || this).parentWindow || window).event;
return event;
}

function registerEventHandlerWithType(aEventType, handlerFnc){
var handlers = getHandlersForEventType(aEventType)
handlers[handlerFnc] = handlerFnc;
}

function unregisterEventHandlerWithType(aEventType, handlerFnc){
var handlers = getHandlersForEventType(aEventType);
/* if this handler is not registered*/
if(handlers[handlerFnc]==undefined) {
return;
}
delete handlers[handlerFnc];
}

function handleEvent(aEvent){
aEvent = detectEvent(aEvent);
var handlers = getHandlersForEventType(aEvent.type);
var diagMsg = "";
for(var handle in handlers){
// construct the method call from the function name and pass parameter
eval(handle)(aEvent);
}
/* stop the event bubbling now, this ensures browser compatibility */
if(typeof aEvent.cancelBubble != undefined){
// IE event model
aEvent.cancelBubble = true;
}
if (aEvent.stopPropagation){
// Gecko event model
aEvent.stopPropagation();
}
}

return {
/* public methods that are being exposed */
registerEventHandlerWithType: registerEventHandlerWithType,
unregisterEventHandlerWithType: unregisterEventHandlerWithType,
handleEvent: handleEvent
}
}

/**************************************************************************
Event Handler definition ends
**************************************************************************/

function observeEvent(aEvent){
HANDLER.handleEvent(aEvent);
}

How to post code?

Markup tags are detected using '<' and '>'. So these are skipped when encountered. This is the reason we don't see content making use of these symbols (well-formed xml content for example). Indentation is another aspect. Luckily the '<pre>' tag comes to our rescue. If we want to paste some code, we need to escape the '<' and '>' so that they are rendered properly. Rather than doing it manually, there are certain resources that help us accomplish the same. Certainly we can write our own custom code, another lazy way I found out is to use the following

http://www.bware.biz/default.htm?http://www.bware.biz/DotNet/Tools/CodeFormatter/WebClient/CodeToHtml.aspx

http://www.stanford.edu/~bsuter/js/convert.html

Robust Web Design - part 4 -last

Beware of java programmers in guise of java script programmers


Will you ever use a Japanese interpreter for your trip to China? Just because things appear the same doesn’t mean they are the same. One may understand things, but is it sufficient? I personally feel that there are two styles of programming, sniper style and landmine style. One has precision and the other has visibility. Good programmers use precision, they know what to do and the impact of what they are doing. Others still in the learning cycle, try to apply intution or make assumption. Learning languages helps, learning the purpose of the language is saviour. Ever heard about the ‘Golden hammer anti-pattern’? It is important to know what to use and where to use it.

Java script shares a lot in common with Java, human minds being very adaptive at least perceive so. The reality is different. It is easier for a Java programmer to master java script. All I am interested is, if any effort is invested in that direction.

Philosophical differences between Java and Java script:

1. Java is static typed, java script is dynamic; there is no type checking in place so use of proper naming convention is vital.
2. Java is application language with support for class invariants. Java script was designed to live in web browsers (I know jdk 6, FX and desktop support, but please…). Web browsers are not supposed to support business invariants, they support view (V of MVC). If someone uses Math library in java script, take him into custody.
3.Java doesn’t support closures (not yet till jdk 6). Java script does. In case, you are wondering, Closure is just a set of statements that can be passed here and there (as parameter). It is just a different style of doing things, you know!!
4.Java is inherently object oriented most of the time with a central control structure. Java script on the other hand is functional and event-driven.

One symptom of java programmer not doing his homework, is use of ‘==’/’!=’ in place of ‘===’/‘!==’.

Namespace contamination horrors


A good java script programmer tries to keep namespace contamination to a minimum by using object based style. ‘Revealing module pattern’ and ‘Singleton’ are some examples. We can also get huge performance benefits by reusing objects than recreating them. Magic numbers in code can be kept to a minimum using the above. In fact a good piece of work also show cases, cross browser compatible event handling.

Some references: On java script patterns

We can achieve similar things in CSS by using a unique template id and referring to it in all selectors. This non-semantic declaration is worth its cost. When programming in a large team, these decisions become important.

The class of web 2.0: IE, Mozilla, Opera…


Each of us is unique, that aspect makes ‘each’ of ‘us’. So are browsers. Some prominent aspects I left of earlier are summarised here

Event model

W3C standard even model speaks of three phases capture, target and bubble. Not all browsers support this. So there is a need to hack into the event model and support the least common factor. A custom event model should also prevent function overriding, (usually happens when two different functions are tied to the same event)

Dom model

Not all browsers support Dom functions uniformly. We need to have a custom common wrapper library for the most useful ones and refer to the library. These assets can be reused across assignments.

Xslt wonder

Java script is not the only way to present a view. Certain sections of the user community/application may be reluctant to use scripts. Xslt is the answer for such. It is rich specification with support for reg-ex as well!

AJAX, JQuery, DOJO and others


We discussed the group of java script dissidents; as the world exists we also have a section of aficionados. These guys are those who enjoy the privilege of huge broadband, fast processors and humungous main memory when compared to the past era (read 4 years ago). Writing our own scripts and testing for cross browser compatibility is painful. Why not ask someone else to help us out here? Dojo, JQuery, YUI from yahoo, GWT from Google, JMaki and several others have been targeting these goals.

Robust Web Design - part 3

Third posting

CSS – Domino effect


A home made avalanche vs. a child’s play kit? Is something I used to wonder when I first understood the purpose of CSS. I would never teach CSS to someone who is starting web-design, who cares about consistent styling or the fact that the way content is uniformly laid, ok I was kidding. These things are better learnt by feeling the flare, the flare of inconsistent design, the wrath of the end-user, the harm to ones own pride, the legend of Zelda, the story of war craft…(ok I exaggerated a bit).

CSS even its simplest form (inline style definition) shows its’ merits. Forget about layouts, forget about cross browser compatibility. The amount of code that is reduced (read more coffee breaks) is itself rewarding. “The lesser the code, the fewer bugs” - a well known adage. I used to correlate CSS with Dominos. Remember those videos on youtube. Anyone who designs a large project faces the same challenges. Things rarely go so well when put to practice. So there are certain firewalls, redundancies put in place. CSS is essentially huge collection of domino chips, with provisions for firewalls and redundancies (read CSS selectors). These provisions allow certain chips (rules) to take precedence over others. Each chip (rule) causes an effect (sets style properties). The game is to place the chips and firewalls appropriately. The challenge is the game floor. Not every stadium/court is the same! There are certain tricks and tips to raise our bar, when playing in not so friendly arenas (hacks). These tricks work well for that given court alone and don’t go well with the big picture.

A check list for the techies:

  • Learn your selectors

  • Negotiate for the most recent browsers and restrict their number (I know I sound like a weasel)

  • Overwrite browser defaults

  • Negotiate for the minimum window size, especially height of the scrollable content in px. May be critical for java script disabled scenarios. Fluid layouts need specs in ems

  • Avoid mixing margin & width attributes. Inconsistencies across browsers rise from the misinterpretation of box-model

  • Alternatively; use padding, and/or border styles with width and color matching the background; to achieve the same effect

  • Avoid tables for layout. Most accessibility problems rise from this fact

  • Seek dispensation for complex UI features. Almost, all known browsers till date fail the Acid tests. It is difficult to achieve standard compliance using non-standard compliant user agents

  • Avoid CSS expressions

  • Try to build your styles based on the least common selectors

  • Test your styles across browsers



a. Test for well formed content in absence of CSS
b. Test for accessibility
c. Test for text enlarge, compact scenarios
d. Avoid classitis and divitis. Use grouped declaration of selectors and pseudo declarations. Divitis may not be avoided always
e. Document the use of extraneous divs (if any being used for layout)
f. Separate styles based on usage pattern i.e. layout, color, font-styles
g. Use a namespace to avoid style-conflict


Horror of hacks


Ever heard of 3 pixel jog? Knowing your browser is of paramount importance. There is a difference in addressing symptoms and addressing the cause. Which one would you prefer? There are a huge number of resources that speak about these. I personally like ‘CSS Mastery’ by Andy Budd and ‘Pro CSS Techniques’ from Apress. I haven’t read others, but I feel one or two books help you realise the game.

Robust Web Design - part 2

Second part of the post...

Russian dolls, Onion skins and the purpose of existence


All boxes look the same, but are they the same? Suppose I have magic wand that with me, that lets me resize things and 100 boxes and if I need to fit all the boxes into a single box; all I had to do is pick two boxes, change the size of one to accommodate other, easily said. What about html mark-up? Well think of a trying to fit a coffin into a food container, sounds funny! The odd feeling is because of the fact that we try to relate containers with content. They have a purpose. Do we know the purpose of html containers?

Valid mark-up

God, created heaven and earth, and W3C dictates web standards. Learning the rational behind standards, helps better appreciation and usage. Two broad level box model types are Block and Inline. There are other finer classifications of course, for example six box models, which are: inline, inline-block, block, table, absolute, and float. W3C also has an html validator application, which notifies us of the violations. Doing early and frequent checks for compliance always helps. Anyone who has stacked up laundry for the weekend knows this.

A compliance, AA compliance, AAA compliance


Inaccessible web sites are politically incorrect, legally liable and may cause potential loss of revenue. Certain technologies are not yet deemed accessible (like flash). Just acknowledging the guidelines while designing the site, makes the developers’ life easier. One can always use this as an excuse for excluding fancy stuff of course! Accessible websites make developers more pragmatic, and avoid gloss.

This works perfectly fine on my machine – Unfortunate reality


Above is a typical complaint from a software developer – a myth – something to be frowned upon. At least I did use it once in my early life as a college pass out. Most of the time, a bad design decision or a weird environment issue causes this. Unfortunately, when it comes to web design, we have a number of variables that make us acknowledge this statement. Did the developer use CSS expressions, did the developer face this on Mac/Windows, what was the browser, what was the resolution, which version of the software is used …. did the butterfly flapped its’ wings, did Microsoft sneeze.

PNG, SVG, Flash

Not every browser is the same, ACID2 and ACID3 tests give more insight into this issue. How can we have standard code when we don’t have standard compliant user agents? - a million dollar question. The answer: is the whole reason why the client hired you. PNGs are not supported on IE, try using transparent shadow affects, you will know. So are several other technologies across several other browsers.

Robust Web Design - part 1

For a change I will speak of Dos and not about Don’ts. Who likes a wailing moron anyway?

On a mark, get…


The first thing to do before we start off into code is to acknowledge and assess ones own competencies. Most often, I see people, who fool themselves into the misconception, that web-design is simple. Well they are not exactly guilty. Most often one can see that HTML is no rocket science. A two day reading of the material is sufficient. Any design can be realized with the knowledge of tables. The challenge is convincing oneself that there are things beyond the obvious, and learning is never obviated (warning: obviate isn’t a synonym of obvious). The litmus test I would use: Ask the developers if they are aware of something called quirks mode.

The first phrase is DOCTYPE and a great leap for design


Neil Armstrong landed on moon, and it was rocket science. Now DOCTYPE doesn’t leave a trail of fire, nor is a achievement telecasted globally. Besides that, DOCTYPE is one part that is capable of setting you on fire and telecast your monumental failure across the group.
The possible DOCTYPE declarations and their effects are well presented in Quirks_mode
My suggestion, use XHTML strict in standards mode. Note that having any comments before DOCTYPE declaration in IE trigger quirks mode. One may occasionally wonder why go to such extremes, the answer is simple: Invest and Profit or Ignore and Pay later. A strict standards adherence guarantees minimal deviation across browsers. ‘Almost strict’ is also desirable though.

Raise and Fall of mark-up – XHTML


The most interesting thing about standards is that they promise huge benefits and deliver little. XHTML is one aspect of standards that raises my suspicions. Just to avoid the notoriety of being an eccentric designer, use XHTML. Who knows, somewhere down the line there may come a day. I bet that Michael Faraday never dreamt of the modern marvels of electricity the day he discovered it.

Thursday, July 10, 2008

Good practice, bad practice

When I was young, I had a nasty habit of biting finger-nails. My parents tried hard to convince me that it was bad, I couldn’t' see what was wrong with that. After all, those are my fingers, aren’t' they? Before I tell you how I quit that habit. I got to tell you, how amused I feel when I think about it. To may amazement, when I get to see people writing crappy code around, I don’t' feel equally amused. Narcissistic SOB, I may be.

I most amusing part is the climax, where you confront them. You get to hear interesting arguments in defence. Some almost child like ones: "But the final affect is the same" or "It works, and what you are telling is not very straight forward". Some rather thoughtful ones: "It’s already tested". Seldom some arrogant ones: "Why doesn’t' he/she do it". Most of the times, the final result is a compromise. The times one sees beautiful code, one can assume that there is egoistic SOB down under. I like these guys. They write code as if they have discipline imbibed into their cerebral cortex, only to find that they can be as sloppy as your neighbour’s cat.

Now don’t' get me wrong. I know that people learn from mistakes. Adaptability is a virtue. The SOBs have had their share of misgivings. Remember the scene from movie MATRIX where neo jumps of the building! no one jumps the first time, not even the ONE. Taking shortcuts harms, but shortcuts are supposed to be short. It is like driving through city center. When you are new to the city, don’t' take shortcuts. Keep to the main road. That is the greatest shortcut. People tend to ignore the greatest shortcut of all, do your research, don’t' wait till you see the river, find out where the river is even before you reach.

A wise man once said that there are no dumb questions. Let me blabber about what I feel about "The final affect is the same". Well is it, is it really. We are forgetting the fact, that two months down the line, when some miscreant changes requirements or finds a new defect. I wouldn’t' like to waste my energy. Nor would I like my brotherhood of #£$$% (fill your own stream) to suffer. Most seriously, I am willing to spend two days right now than slog late into nights for months, later on. The final affect is on you dear, and you effect the affect.

For, "It works, and what you are telling is not very straight forward". You are damn right. So does walking. Why learn cycling or drive a car or take a flight. Knowing things is difficult, but when it can give some real soul satisfaction. Ask any teenager fiddling an engine. "It’s already tested" is the most difficult one to justify. The only excuse I have is that it makes you fall out of habit. For "Why doesn’t' he/she do it", trust me this isn’t' a flight to Moon, even that was repeated. (Or is it?)

The only difference between the nutcases who organise their stuff with the rigmarole of a fascist and the rest of the world is the same one between those willing to till the soil, creates a fertile bed and between other gatherers. All we are speaking of is some interest, planning, discipline and investment.

Popular Posts

Labels

About Me

Well for a start, I dont' want to!. Yes I am reclusive, no I am not secretive; Candid? Yes; Aspergers? No :). My friends call me an enthusiast, my boss calls me purist, I call myself an explorer, to summarise; just an inquisitive child who didnt'learn to take things for granted. For the sake of living, I work as a S/W engineer. If you dont' know what it means, turn back right now.