Thursday, March 14, 2013

Examining blackbird.js

The code to blackbird.js can be found here. Today, I will examine the inner working of blackbird.js, line by line.

To start off with, let's understand the self-executing anonymous function.

(function () {
    ... some code
})();

The use of it, helps to provide function level scoping while making the code executing on its own. For more detailed explanation, refer to this nicely written blog.

Next, at the top level within the main function, we can see that there are some variables defined, including cache array, and objects like classes, profiler and messageTypes. At the same time, some inner functions are there: generateMarkup, clickControl, isVisible, getState, addEvent, and removeEvent. The window object is set with a namespace, i.e. the log object with methods such as toggle, clear, debug, warn and profile. These methods provide the API of the library. The initialization code is performed on window's load. This is achieved by calling addEvent with window, 'load' event and the callback function as the arguments. The addEvent & removeEvent code look a bit long but have good reasons. The main idea is to be cross-browser compatible.

The initialization code requires some describing.


addEvent(window, 'load',
/* initialize Blackbird when the page loads */
function () {
    var body = document.getElementsByTagName('BODY')[0];
    bbird = body.appendChild(generateMarkup());
    outputList = bbird.getElementsByTagName('OL')[0];

   backgroundImage();

   //add events
   addEvent(IDs.checkbox, 'click', clickVis);
   addEvent(IDs.filters, 'click', clickFilter);
   addEvent(IDs.controls, 'click', clickControl);
   addEvent(document, 'keyup', readKey);

   resize(state.size);
   reposition(state.pos);
   if (state.load) {
       show();
       document.getElementById(IDs.checkbox).checked = true;
   }

   scrollToBottom();

   window[NAMESPACE].init = function () {
       show();
       window[NAMESPACE].error(['', NAMESPACE, ' can only be initialized once']);
   }

   addEvent(window, 'unload', function () {
       removeEvent(IDs.checkbox, 'click', clickVis);
       removeEvent(IDs.filters, 'click', clickFilter);
       removeEvent(IDs.controls, 'click', clickControl);
       removeEvent(document, 'keyup', readKey);
   });
});

Line by line, first it grabs the body element, then append to it the generated markup. The outputList element is set. Next, events are registered for clicking the checkbox, filters, additional controls, and key ups. Base on the current state, the log display is resized and repositioned. If indicated to load, the display will be shown and the checkbox checked. Then the log content is scrolled to the bottom. The init method on window namespace object is defined. Finally, window on unload will remove the before-mentioned event registration.

In the next blog, we'll go and visit the individual functions and the relevant variable data.

No comments:

Post a Comment