Posts Tagged ‘programming’

For Robomen: OO Conversation

Wednesday, February 4th, 2009

R: Maybe I should rename Blog to BlogContainer for consistency. Because what is a blog? It’s just a collection of Posts. There is no Blog.
A: I don’t think so. Following that convention, you could say that there is no Person. No Human. There is only PersonContainer which contains meat and soul.
R: …and we are all the instances. Probably you are a class inheriting from the PersonContainer. :D
A: What!? Then what are the instances of me? My images?
R: You are singleton :cool:

Recently I heard somebody saying I am crazy.

For Robomen: “Website is Under Construction. Please Come Back Later”

Friday, December 26th, 2008

Iteratively developed web projects are constantly updated. Sometimes the file structure has to be changed. Sometimes a new table is added to the database schema. Sometimes the data has to be massively changed. In a simpler case, HTML templates and style is changed. Usually, a more complex upgrade takes half an hour or even an hour, and the visitors should see “Under Construction” page instead of the normal site during the process, because the nobody should see broken view or corrupt data by accident while writing something to the database at that time.

Under Construction

A good practice for Apache web server users is to have a couple of configuration files which would be activated alternately, depending on whether the website is accessible to everyone, or is in the upgrade state. Once Tomas gave me an idea to create such configuration for the upgrade cases that others saw “Under Construction” page and I could browse the content and test if everything looks alright. So did I.

Apache lets you set the web server configuration on the directory level using .htaccess files. For the important projects I have files .htaccess_live and .htaccess_under_construction containing different settings in the root directory of the website. When I need to change the state, I copy the appropriate configuration to the .htaccess file:

cp .htaccess_under_construction .htaccess

or

cp .htaccess_live .htaccess

The content of the Apache configuration file .htaccess_live is something like this:

# index.html and index.php represents the directory by default
DirectoryIndex index.html index.php
<ifmodule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    # If the page was accessed by example.com, then redirect the request to www.example.com
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com$1 [R=301,L]
</ifmodule>

Whereas the content of .htaccess_under_construction is this:

# index.html and index.php represents the directory by default
DirectoryIndex index.html index.php
<ifmodule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    # If the page was accessed by example.com, then redirect the request to www.example.com
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com$1 [R=301,L]

    # if the IP address of the visitor is not 1.2.3.4 and the requested directory is not media,
    # then redirect the request to the file temporarily-offline.html
    RewriteCond %{REMOTE_HOST} !^1\.2\.3\.4
    RewriteCond %{REQUEST_URI} !/temporary-offline\.html$
    RewriteCond %{REQUEST_URI} !^/media
    RewriteRule .* /temporary-offline.html [R=302,L]
</ifmodule>

These configurations use the mod_rewrite module. RewriteCond defines the conditions which should be met to execute the redirect of request set by RewriteRule. The parameters in the brackets have the following meaning:

  • NC (no case) – use case insensitive comparison.
  • R=301 – redirect the request with code 301 “Moved Permanently”.
  • R=302 – redirect the request with code 302 “Moved Temporarily”.
  • L (last rule) – this is the last rule, so don’t execute the rest.

You can find your own IP address in one of the plenty What’s My IP services.

Now it’s clear how to technically set the temporary “Under Construction” view. The next thing, which seems quite important to me, is to show an appropriate temporary page. I personally like such error and system-message pages which describe the problem in a non-technical and visual way like twitter.com does, or the ones showing a video or something interactive to make me busy while the upgrade is being done.

For Robomen: Equalizing Column Heights by CSS

Friday, December 19th, 2008

Since the times when it got not recommended to use tables for layout, from time to time I have been facing a problem how to set the same height for columns of varying amount of content. There were suggestions in the web to use vertically continuing background image with the colors of the columns or an additional Javascript, which finds the highest column and sets the same height for the others. But these variants were too limited and too heavy (let’s leave the Javascript for more important functionality that the presentational tweaking). Just a few days ago a colleague working with HTML templates, showed me a better solution by Alex Robinson.

My terminology in this text is as follows: a container is an HTML element which children will be called columns when they’re visually laid out horizontally next to each other. The standard examples of containers and columns could be those:

  • Page layout horizontally divided into, let’s say, three parts. Three div elements wrapped by the fourth div.
  • Horizontally displayed navigational menu. The element ul with its kids li.
  • Gallery photos drawn into a grid. div elements as small containers of photos with their descriptions and links laid out in another div representing a row.

The elements called columns are drawn up horizontally by CSS in all of those cases: they have defined widths and are moved to the left or right side by float: left or float: right. That’s enough talking about column layouts. Let’s have a look at the problem and its solution.

You might think, that you can set equal heights for different columns by the CSS parameter height, but you should take in mind that the visitor of the website can change the text heights at the View → Text Size settings. The times of static websites are over and nowadays usually we work with varying user-generated content. So the column will have a varying height which will depend on the amount of containing content by default.

Equalizing the columns

The solution by Alex Robinson is to define an insanely huge bottom padding padding-bottom for a column and then to distract the distance by a negative bottom margin margin-bottom. In case you forgot the CSS box model, I remind you, that the background of an HTML element belongs to the content itself and to its padding. If you define overflow: hidden to the container of the columns, the elements will look visually of the same height. The size of the insanely huge padding should be such a height which is never smaller than the content of the column. So if we are talking about menu items of 1 to 3 rows of text, then 100px is enough.

#block_A, #block_B, #block_C {
	padding-bottom: 32767px;
	margin-bottom: -32767px;
	}
#container {
	overflow: hidden;
	}

You can read about different exceptions of this trick in different browsers at Position Is Everything. There are also some other interesting solutions which I’m gonna check (but I won’t write a separate post about that :D ). The varying heights should be taken in mind not only by template creators, but also by the graphical web designers. But that’s already another theme.. And I’m gonna bake Kūčiukai now.

The Features of Web Apps

Monday, November 17th, 2008

A decade ago when Internet Explorer was the absolute winner in browser wars, it seemed to be cool to produce internet projects which pop up in new windows, hide the address bar, start playing favorite music, or change the color of scroll bars. There weren’t as many possibilities as nowadays, so I wanted to try all new flowers and butterflies and show them to others. But times and values changed. The standards of internet technologies were created, many new browsers were invented, new possibilities in phones and other devices were introduced. And so the web became a social phenomenon, the new lifestyle or at least helper for plenty of people. Different applications which had been installed on desktop computers, moved to remote servers. Nowadays web apps usually expose the full potential of the global network.

Web app logos

For better understanding, web apps are such applications which we use in internet browsers, for example, webmail, e-shops, auctions, wikis, or multiplayer online games. Recently, Robert O’Callahan from Mozilla wrote about good practices while creating web applications, regardless of the chosen technologies.

Clever URL addressing. The URLs should be organized in such a way that different parts of the web app could be saved as a del.icio.us bookmark or sent to a friend. For example, I know that when I enter http://mail.google.com/mail/#drafts, I will get to the Drafts of my google mail.

Sandboxes. The new users of the system should be provided with a safe demonstrative environment also known as sandboxes. They could test different functions there without breaking the important data. For example, PayPal has a sandbox for online merchants and CMS Made Simple has its demo version for potential users.

Browser apps should be used in the context of the browser. The buttons “Back”, “Forward”, “Refresh”, and “Stop” should function in the browser as well as the status bar, history, etc. The blocking of contextual menu or forced opening in a new window doesn’t add any protection against copying nor other value.

The apps should have inner structure that enables the features of the browser and it’s helping tools. The users should have an ability to manipulate the content or layout for their convenience: resize the text, search inside of a page, apply custom style or improve the usability by own scripts using either Greasemonekey (or similar plugin) or bookmarklets. The content of the web app should be indexable in search engines. Looking from the security perspective, all logic happening in the browser should be revalidated in the server.

Of course, most of those features can be applied not only to web apps, but also to social networks and to simple informative websites. We’ll see how everything evolves in the future, but at the moment the direction is clear: internet stimulate creativeness and openness. And I like it.

Combined Event Handlers

Thursday, January 31st, 2008

Tonight you are having dinner with your date at your house. The table is prepared with a pair of glasses, a bottle of wine and two candles. You are cooking “Gemisto Kalamari” according to the Greek recipe. And then the doorbell rings. You take the pan off the range, then you switch on the light in the corridor, then you look at yourself in the mirror, then you open the door, and finally you let your date in. What happens next is only between you and your chosen one. If you are a Nerd, you might notice associations here with event handling. One event like doorbell ringing triggered 5 different autonomous functions following after each other. What is the best way to handle that in interpreted programming languages?

Let’s look at some more technical example. Let’s say, there is a website with tabbed navigation. If Javascript is disabled, the tabs (being actually normal hyper links) open as new pages. Otherwise they load content dynamically using Ajax concept. Somebody clicked on a new tab. Then the handler of that clicking event triggered multiple functions like highlighting the new tab instead of the previous, showing a rotating circle as a progress indicator inside of the area for content, canceling the default link functionality, and requesting for the new content.

All that could probably be implemented using code similar to this:


function openTab(oEvent) {
    activateTab(oEvent);
    showProgress(oEvent);
    cancelEvents(oEvent);
    loadTabContent(oEvent);
}
for (i=0; i<iAmountOfTabs ; i++) {
    document.getElementById("tab_" + i).onclick = openTab;
}

If there are many different Ajax-based functionalities like ratings, tagging, comments, chat, and maps, the website will probably have many functions which purpose is just combining other autonomous functions into sequences. It would be nice to have a mechanism to list out all the related event handlers in a row, like this:


for (i=0; i<iAmountOfTabs ; i++) {
    document.getElementById("tab_" + i).onclick = queue(
        activateTab, showProgress, cancelEvents, loadTabContent
    );
}

All that is possible as functions are objects that can be passed to other functions. The queue should be a function which would return another function passing the Event object to the listed functions. Let’s not limit the number of arguments just to one, but rather pass all of them for flexibility. The source code for the queue might look like this:


function queue() {
    var aFuncs = arguments;
    return function() {
        var aArgs=arguments;
        for (i=0, iLen=aFuncs.length; i<iLen ; i++) {
            var oF = aFuncs[i];
            oF.apply(this, aArgs);
        }
    }
}

The same mechanism could be used on the server side or desktop applications when programming combined event, hook or signal handlers. For example, here is an analogous function in python:


def queue(*funcs):
     def joined(*args, **kwargs):
         for f in funcs:
             f(*args, **kwargs)
     return joined

The queue function could be easily modified to call the next function from the sequence, only if the previous one was executed successfully and returned positive value. Or the result of each function could be additionally passed to the next one. All that would be up to you. But… It’s all over now. You are lieing dead on the ground. You should have never opened the door without looking through the peephole. Your date was a serial killer and shoot you with a machine gun just after opening the door. Somebody had a little bug in the workflow :P . Game over!

Tips on Javascript Widget Accessibility

Monday, January 14th, 2008

Rich GUI is one of the requirements of nowadays web. The look and feel of websites is getting closer to desktop applications. The widgets are getting more and more intuitive. But the web developers, as well as customers ordering the web projects, should always keep accessibility and semantics in mind. The web is information at first and impression afterwards.

Client-side technology layers: Javascript and CSS on top of XHTML.

Technologies should enhance the real world, but not vice versa. Therefore, as the owner of the content, you should be interested to distribute the information in all available ways. The content should be accessible in standard modern browsers as well as in Javascript-disabled browsers, screen readers, or small-screen devices like PDAs and cell phones. The presentation (CSS) and special effects (Javascript) should go on top of the content (XHTML). These parts should be separated into different files and not mixed-up. The general rule of thumb tells that if you switch off the style, images, Javascript, or all together, the visitor should still be able to read the content and navigate through the website. Imagine, that you came to a concert in a different city and you need to find out what buses are going to the concert hall. Then you open the local website of the public transport system in your mobile phone and check your traveling route. If this website is not accessible to you because of obligatory specific Javascript widgets which are not supported by your mobile, you will probably be late to the concert and your day will be ruined.

The semantic web is a concept of rules for informational data, which would allow represent, query, and modify data using different technologies. Instead of unreliable screen scraping for getting specific information from the page, it should be possible to parse the content using the DOM and to get the whole structure of the page. This is not only useful for search engines, but also for third-party web and desktop applications that may reuse your content in different mashups. For example, if have a simple informational website for the restaurant you own, with its location and probably a dynamic and nice map, there could be another company which would make a web crawler collecting information of different restaurants and hotels, and parks, showing them in one combined map with ratings of each place, comments, and recommendations. If the content of your website is not semantic, you’ll hardly get additional attention from third-party projects.

No matter, what the business model for the website is, if the company is future-oriented, the website should have the structural content separated from presentation and logics. And the content should be accessible and navigable without Javascript nor CSS. All the rich GUI effects should be added additionally by Javascript, when it is enabled. Forget all the tutorials and examples creating content on the fly with document.write or adding event handlers for HTML element directly in the markup. The Javascript should be included from separate files and it should influence the content using DOM after the page is loaded. This concept is called unobtrusive Javascript. The separation of different layers means also faster loading as Javascript and CSS files are usually downloaded once and taken from the browser cache for other requests.

DON’T:


XHTML:
<a href="http://aaiddennium.com/blog/"
onclick="window.open(this.href,'','width=800,height=600');return false">
My Blog
<script type="text/javascript">
/* <![CDATA[ */
document.write("(opens in a new window)");
/* ]]> */
</script>
</a>

DO:


XHTML:
<a href="http://aaiddennium.com/blog/" class="new_window">
My Blog
</a>

Javascript (included from a separate file):
window.onload = function() {
    var aElems = document.getElementsByTagName("a");
    for (i=0, iLen=aElems.length; i<iLen; i++) {
        var oEl = aElems[i];
        if (oEl.className.match(/\bnew_window\b/)) {
            var oT = document.createTextNode("(opens in a new window)");
            oEl.appendChild(oT);
            oEl.onclick = function(e) {
                if (!e) var e = window.event;
                var oLink = e.target || e.srcElement;
                window.open(oLink.href, "", "width=800,height=600");
                e.cancelBubble = true;
                e.returnValue = false;
                if (e.stopPropagation) e.stopPropagation();
                if (e.preventDefault) e.preventDefault();
            };
        }
    }
}

Moreover, there is a concept of creating fully functional website without special effects and then adding Javascript to change the default links to Ajax-based content loaders. This concept was called Hijax by Jeremy Keithin in his book Bulletproof Ajax. However the Hijax approach has it’s disadvantages as well. For example, the standard Back/Forward functionality makes no sense with Ajax data loading. And it’s pretty expensive to duplicate all the functionalities making one server-side and one client-side approach.

I would say, that the usual link navigation should be used in most cases, and Javascript should be added only as specific widgets or for specific pages. Javascript can overwrite the default functionality. For example, external links can be opened in new popup windows by Javascript, or some small forms can be opened in new Ajax-based dialog boxes. The original link, turned into Ajax-based-functionality switcher, in some cases might lead to a new page, telling how to enable Javascript or where to get a modern browser. Or it can be a hash (#) link, leading to some place with information in the same page.

Each page should provide information, that the website is best experienced when viewing with Javascript-enabled modern browsers. This message could be hidden dynamically by Javascript on the page load, or even better, it could be written into the <noscript> tag which is shown when there is no Javascript. If you choose to hide the message by Javascript on the page load, you might dislike the flickering of the view as the message shows and then disappears. You can avoid that flickering, dynamically adding display:none not to the containing element by id after the page loaded, but to the additional CSS rule for the selector by that id while the page is still loading. The head section of the HTML document is always executed before the body is shown.

DON’T:

window.onload = function() {
    document.getElementById("warning_js").style.display = "none";
}

DO:

function dyn_css_rule(sSelector, sCssText) {
    var oCss = document.styleSheets[0];
    if (oCss.insertRule) {
        oCss.insertRule(
            sSelector + " {" + sCssText + "}",
            oCss.cssRules.length
        );
    } else if (oCss.addRule) {
        oCss.addRule(sSelector, sCssText);
    }
    return sSelector + "{" + sCssText + "}";
};
dyn_css_rule("#warning_js", "display:none");

Moreover, you should never dynamically modify the style of HTML elements directly. CSS is the responsibility for presentation layer, not the logics layer. Javascript should manipulate semantical class names. Then the presentation layer decides what to do with, let’s say, not important elements: to hide them, add some transparency, make the font smaller, or move them to different positions.

DON’T:

function toggle_visibility(sId, bVisible) {
    document.getElementById(sId).style.display = bVisible? "block": "none";
}

DO:

function toggle_visibility(sId, bVisible) {
    var oEl = document.getElementById(sId);
    var sClasses = oEl.className.replace(/\s*hidden\s*/g, " ");
    if (bVisible) {
        sClasses = sClasses + " hidden";
    }
    oEl.className = sClasses;
}

Even if you are a professional Javascript coder, it is useful to use Javascript frameworks instead of raw Javascript. The code you write will be cleaner as most boring routines are already implemented in the framework. The development will get faster as soon as you get used to it. And the product will be more reliable as the framework is tested on different browsers by large communities. The framework you choose, should support unobtrusive Javascript approach and strict XHTML. I personally prefer jQuery, but you can choose any other framework which seems easily adaptable for you.

DON’T:

var aElems = document.getElementsByTagName("div");
for (i=0, iLen=aElems.length; i<iLen; i++) {
    var oEl = aElems[i];
    if (oEl.className.match(/\bspecial\b/)) {
        oEl.onclick = special_function;
    }
}

DO:

$("div.special").click(special_function);

When working with Ajax, you should also understand that the speed of Internet is not the same for all visitors. So even if it takes a second for you to load some JSON-formatted data, the same request might take about 15 seconds for another user with sloooow Internet connection. So the website should show different identifiers for different statuses of “initial state”, “loading”, “result”, and “error”. Otherwise the visitor might click on the same widget multiple times trying to make it functioning. And this might lead to accidental duplicates and confusion. Sometimes it might be also useful to have a button for canceling the current request.

It might be strange for you that I didn’t show you how to create any full-featured widget as rating management, auto-completion or some calender. But the purpose of this entry was the introduction to the client-side coding of a better quality. All the rest depends on your creativity and business requirements. The experience comes from practicing.

Further reading:

Control Your Code with Subversion

Saturday, October 6th, 2007

I can’t imagine professional IT project development without source control. No matter whether you’re working on a small personal project or on a large commercial application, source control is something that helps you to manage bunches of constantly changing code among multiple developers. It is so-to-say UNDO functionality in the programming process.

How to manage a project among multiple developers?
Source control has a repository where it holds the developed files and the data of your development process. Each developer works with her own copy of the repository. The basic work under source control looks like this:

  1. You get the files from the repository to your local copy. This process is called “check-out” (for the first time) or “update” (for the next times).
  2. You edit files.
  3. You check the status, what files you’ve changed. If some new files were created, you might add them to the source control as well, or you can set them in the ignore list not to show them in the status report anymore.
  4. Then you send the changes from your copy to the repository. This process is called “commit” or “check-in”.

With each committing, source control creates new versions of your files. The commit generates a new revision which has an incremental number. If you make some mistake, you can always rollback to a previous state of your development by the number of revision or by date the committing was made. With each committing you can (and should) write comments, what was changed for that revision, so it’s much easier to find out to which revision to rollback. Also source control usually can show the changes of the same file between two different revisions.

The repository might be set up either on the same computer or on the distant server. Files can be controlled for one person as well as for a large network of developers.

When a couple of developers modify the same file, the source control tries to merge the changes in the file. If it’s not obvious, how to do that, a conflict is thrown, and developers have to solve it manually. Source control doesn’t accept any conflicts to the repository. They have to be fixed on the local copies before being able to commit.

When the project is developed by multiple people, it is possible to check what changes were done by whom. There are some other functionalities of source control as tagging all the files of the current revision with some string (i.e. release number); creating different branches of the same project, or merging two different branches into one.

From a bunch of source control systems, I prefer Subversion (SVN), as it is full-featured, convenient, stable, and last but not least – it’s free of charge.

At the studio, where I work, we use SVN for CreativeCityBerlin and other Django-based projects. The repository is in a secured server requiring authentication for each user. We use a wide range of SVN clients on different platforms. I usually use the standard command-line SVN client for my own development environment (it’s on Mac OS X) and for the public server (running on Linux) where the websites are hosted. Some of us use ZigVersion SVN client for Mac. Some are using TortoiseSVN for Windows.
Multiple Developers Using Subversion

As a small step towards continuing developing my Halma game and other personal projects, I installed TortoiseSVN on my personal laptop as well. I am not the only person to approve that TortoiseSVN is the most user-friendly SVN client on the Earth at this moment.

It is fully integrated into Windows Explorer and it is very intuitive. All the source-control functions are accessible on the right-click menu. The statuses of the files are marked with indicators attached to the file icons.

Tortoise SVN

After installing TortoiseSVN onto my PC, I created a repository for my Halma game locally. And also as a test I created a public repository on Google code for my Klãva project.

If you haven’t started using any source control, I encourage you to do that ASAP. Version control can be successfully used not only by IT developers, but also by writers, digital artists, or composers.

Simple JavaScript Console

Tuesday, October 2nd, 2007

What I miss while debugging JavaScript in different browsers is a simple FireBug-like JavaScript Console, where you could execute statements for any current page on the fly and get the results immediately.

JavaScript Console

For example:
>>> document.body.innerHTML
"<div class=\"navi\">..."
will return the computed HTML of the current page which might be different than the source of the page, as some JavaScript functions might have modified it.
And
>>> document.cookie="testcookie=testvalue"
will set a test cookie for a document.

As a very simple alternative to JavaScript Console, I wrote a Bookmarklet/Favelet which executes the entered JavaScript statement and returns the result: Simple JavaScript Console. To install it, just add the link to your Bookmarks/Favorites.

If you have some time, wanna practice JavaScript, and make the world a better place to live, I have a task namely for you! Create an open-source cross-browser JavaScript console which could be included into any page by a favelet/bookmarklet. Or create a favelet/bookmarklet which loads and inserts the existing Ext Debug Console into any page on the web.
As a hint how to load a JavaScript file from a bookmarklet/favelet, check the accessible printouts which I created before. The console should return all results in a readable format. All objects should tell what kind of properties they have and all collections and arrays should list their content in a format [item1,item2,item3].

Your code will be reviewed and evaluated. Improvements will be suggested. You’ll be interviewed and proudly blogged. :D

UPDATE! This is my own solution for the task I gave to you: Load Firebug Lite. It works for modern browsers which have no Firebug installed.

For Robomen: Decorators in Programming

Monday, June 25th, 2007

I have been using Python decorators here and there while programming perhaps for half a year already. They are functions wrapping and modifying the results of other functions or methods. Just a few days ago, when the working stress went down, I looked at the inner side of decorators and clarified how they are functioning.

Decorators are used in Python like this:

from some.library import from_cache

def get_answer(argument1, argument2):
    # some calculations
    return answer
get_answer = from_cache(get_answer)

or like this:

from some.library import from_cache

@from_cache
def get_answer(argument1, argument2):
    # some calculations
    return answer

Perhaps you have already understood that from_cache is the decorator for the function get_answer here.

Although the decorator of such a type is the creation of Python, the concept of decorators should work in most interpreted languages (PHP, Java, ActionScript, and others).

I’ll illustrate the inner side of a decorator in JavaScript.

function decorate(decoratedFunction) {
    function wrap() {
        // collecting all the arguments passed to an array
        var args = [];
        for (i=0, len=arguments.length; i<len; i++)
            args.push(arguments[i]);
        // -- the arguments might be modified here  --
        result = decoratedFunction.apply(this, args);
        // -- the result might be modified here --
        return result
    }
    return wrap;
}

function do_something(a, b, c) {
    // ...
}
do_something = decorate(do_something);

This is what happens: the decorator takes the decorated function as an argument and returns another function, in which the arguments of the decorated function are optionally modified, the decorated function is called (not necessarily once), the result of the decorated function is optionally modified, and finally that result is returned.

Thinking not too long, I came to an idea, how a decorator could be practically used in JavaScript. Let’s say, there are plenty of links in a web application, and after clicking on them, some calculations or AJAX requests are executed according business requirements. By the way, each link has its default behavior disabled: the redirect to a page with the alternative information or alternative form for calculations without JavaScript are blocked. So the standard behavior of the link could be disabled wrapping each function of the business logic by a decorator.

function cancelEvent(decoratedFunction) {
    /**
    Decorator, disabling the standard event behavior and
    the triggering of the event for all parent elements
    */
    function wrap() {
        var args = [];
        for (i=0, len=arguments.length; i<len; i++) {
            args.push(arguments[i]);
        }
        e = args.shift()
        if (!e) var e = window.event;
        e.cancelBubble = true;
        e.returnValue = false;
        if (e.stopPropagation) e.stopPropagation();
        if (e.preventDefault) e.preventDefault();
        return decoratedFunction.apply(this, args);
    }
    return wrap;
}

function test(key, value) {
    /**
    "Important" function of business logic, returning an
    "important" result.
    Everything is very serious here.
    */
    return key + " = " + value;
}
// Let's decorate the "important" function. We'll name
// the result differently, so that it would still be possible
// to access the original function
var test_from_link = cancelEvent(test);

window.onload = function() {
    // on the load of the page, let's find the link with the
    // ID "test" and assign a function, managing
    // the onclick event, which
    // will call the decorated function test
    document.getElementById("test").onclick = function(e) {
        alert(test_from_link(e, 'name', 'Aidas'));
    }
}

BTW, I make an assumption in this example, that there are no onclick attributes in the HTML code; there is only semantical content and the JavaScript as well as CSS are located in separate files.

Regarding server-side programming, the decorators could be used to limit the execution of some functions for the visitors not having appropriate permissions; to cache the results of complex calculations or text manipulations and to take that content from cache; and in other situations (if you got any good ideas, drop me a few lines in comments).

That’s it about decorators. OK, I am going to pour some lubricating oil into myself now.

SVG: Hello World!

Monday, November 27th, 2006

Recently I have provided myself with technical literature. For self-education as well as for reference while programming, for personal projects as well as for job-related ones, I purchased books about Flash ActionScript, Unified Modeling Language (UML), and Scalable Vector Graphics (SVG). The O’Reilly’s publishing house rulez.

Here is my first experimental SVG file. Find an Easter Egg 1.


1 Easter Egg is a hidden functionality in a software product, usually created for fun by common programmers without the knowledge of the heads.