Flyweight Pattern – Javascript

Posted: June 22, 2011 in Design Patterns, Javascript, JQuery, Performance
Tags: , , , ,

1. Centralized event handling

This will be used in cases where we have a number of similar elements or structures on a page that share similar behaviour when a user-action is performed against them.

In JavaScript, there’s a known bubbling effect in the language so that if an element such as a link or button is clicked, that event is bubbled up to the parent, informing them that something lower down the tree has been clicked. We can use this effect to our advantage.

Ex: In following example we can bind click event to ul and can handle every li click separately with out binding different functions directly to each li. This will also improve performance by minimizing the DOM access for binding/unbinding and by avoiding the event handling for each element separately.

 <li class=’one’>One</li>
 <li class=’two’>two</li>
 <li class=’three’>three</li>
 <li class=’four’>four</li>
 <li class=’five’>five</li>

stateManager = {
    fly: function () {
        var self = this;
        $(‘ul’).unbind().bind(“click”, function (e) {
            var target = $(e.originalTarget || e.srcElement);
            if (“”)) {
            else if (“li.two”)) {
    handleLIOne: function (elem) {
        //Do your own implementation for first li element click
    handleLITwo: function (elem) {
        //Do your own implementation for second li element click

  1. ramon says:

    also if the list is dynamic, ie items are added and removed, then you dont have to rebind event handlers nor use jquery live()

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s