Krasimir Tsonev is a front-end developer, blogger and speaker. He loves writing JavaScript and experimenting with the latest CSS and HTML features. Author of the "Node.js blueprints" book he is focused on delivering cutting edge applications. Krasimir started his career as graphic designer, he spent several years coding in ActionScript3. Right now, with the rise of the mobile development, he is enthusiastic to work on responsive applications targeted to various devices. Living and working in Bulgaria he graduated at the Technical University of Varna with bachelor and master degree in computer science.

Krasimir's articles

  1. Revealing the Magic of JavaScript

    We use tons of tools every day. Different libraries and frameworks are a part of our daily job. We use them because we don’t want to reinvent the wheel for every project, even if we don’t understand what’s going on under the hood. In this article, we will reveal some of the magical processes happening in the most popular libraries. We’ll also see if we can replicate their behaviour.

    Creating DOM Elements From a String

    With the rise of single page applications, we are doing a lot of things with JavaScript. A big part of our application’s logic has been moved to the browser. It is a common task to generate or replace elements on the page. Code similar to what is shown below has become very common.

    [js]
    var text = $(‘
    Simple text

    ‘);

    $(‘body’).append(text);
    [/js]

    The result is a new <div> element added to the body of the document. This simple operation is done with only one line of jQuery. Without jQuery, the code is a little more complex, but not much:

    [js]
    var stringToDom = function(str) {
    var temp = document.createElement(‘div’);

    temp.innerHTML = str;
    return temp.childNodes[0];
    }
    var text = stringToDom(‘

    Simple text

    ‘);

    document.querySelector(‘body’).appendChild(text);
    [/js]

    We defined our own utility method stringToDom that creates a temporary <div> element. We changed its innerHTML property and in the end we simply returned the first child which in practice is what we needed. It worked the same way. However, we will observe different results with the following code:

    [js]
    var tableRow = $(‘
    Simple text

    ‘);
    $(‘body’).append(tableRow);

    var tableRow = stringToDom(‘
    Simple text

    ‘);
    document.querySelector(‘body’).appendChild(tableRow);
    [/js]

    Visually, on the page, there are no differences. However, if we check the generated markup with Chrome’s developer tools we will get an interesting result:

    Creating a DOM element from a string

    It looks like our stringToDom function created just a text node and not the actual <tr> tag. But at the same time, jQuery somehow managed to do it. The problem is that the string containing the HTML element is run through a parser in the browser. That parser ignores the tags that are not placed in the right context, and we get only a text node. A table row without a table is not valid for the browser.

    jQuery successfully solves the problem by creating the right context and extracts only the needed part. If we dig a bit into the code of the library we will see a map like this one:

    [js]
    var wrapMap = {
    option: [1, ''],
    legend: [1, '
    ', '

    '],
    area: [1, '
    ', '

    '],
    param: [1, '', ''],
    thead: [1, '

    ', '

    '],
    tr: [2, '

    ', '

    '],
    col: [2, '

    ', '

    '],
    td: [3, '

    ', '

    '],
    _default: [1, '

    ', '

    ']
    };
    wrapMap.optgroup = wrapMap.option;
    wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
    wrapMap.th = wrapMap.td;
    [/js]

    Every element that requires special treatment has an array assigned. The idea is to construct the right DOM element and to depend on the level of nesting to fetch what we need. For example, for the <tr> element we need to create a table with a <tbody> child. So, we have two levels of nesting.

    Having a map, we have to find out what kind of tag we want in the end. The following code extracts the tr from <tr><td>Simple text</td></tr>

    [js]
    var match = /<\s*\w.*?>/g.exec(str);
    var tag = match[0].replace(/</g, ”).replace(/>/g, ”);
    [/js]

    The rest is finding the proper context and returning the DOM element. Here is the final variant of the function stringToDom:

    [js]
    var stringToDom = function(str) {
    var wrapMap = {
    option: [1, ''],
    legend: [1, '
    ', '

    '],
    area: [1, '
    ', '

    '],
    param: [1, '', ''],
    thead: [1, '

    ', '

    '],
    tr: [2, '

    ', '

    '],
    col: [2, '

    ', '

    '],
    td: [3, '

    ', '

    '],
    _default: [1, '

    ', '

    ']
    };
    wrapMap.optgroup = wrapMap.option;
    wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
    wrapMap.th = wrapMap.td;
    var element = document.createElement(‘div’);
    var match = /< \s*\w.*?>/g.exec(str);

    if(match != null) {
    var tag = match[0].replace(//g, ”);
    var map = wrapMap[tag] || wrapMap._default, element;
    str = map[1] + str + map[2];
    element.innerHTML = str;
    // Descend through wrappers to the right content
    var j = map[0]+1;
    while(j–) {
    element = element.lastChild;
    }
    } else {
    // if only text is passed
    element.innerHTML = str;
    element = element.lastChild;
    }
    return element;
    }
    [/js]

    Notice that we are checking if there is a tag in the string – match != null. If not we simply return a text node. There is still usage of a temporary <div>, but this time we are passing the right tags so the browser can create a valid DOM tree. In the end by using a while loop we are going deeper and deeper till we reach the wanted tag.

    Here is a CodePen showing our implementation:

    See the Pen xlCgn by Krasimir Tsonev (@krasimir) on CodePen.

    Let’s continue by exploring the wonderful AngularJS dependency injection.

    Revealing AngularJS Dependency Injection

    When we start using AngularJS it impresses with its two-way data binding. The second thing which we notice is its magical dependency injection. Here is a simple example:

    [js]
    function TodoCtrl($scope, $http) {
    $http.get(‘users/users.json’).success(function(data) {
    $scope.users = data;
    });
    }
    [/js]

    That’s a typical AngularJS controller. It performs an HTTP request, fetches data from a JSON file, and passes it to the current scope. We don’t execute the TodoCtrl function – we don’t have a chance to pass any arguments. The framework does. So, where do these $scope and $http variables came from? It’s a super cool feature, that highly resembles black magic. Let’s see how it is done.

    We have a JavaScript function that displays the users in our system. The same function needs access to a DOM element to put the generated HTML, and an Ajax wrapper to get the data. In order to simplify the example, we will mock-up the data and the HTTP requesting.

    [js]
    var dataMockup = ['John', 'Steve', 'David'];
    var body = document.querySelector(‘body’);
    var ajaxWrapper = {
    get: function(path, cb) {
    console.log(path + ‘ requested’);
    cb(dataMockup);
    }
    }
    [/js]

    We will use the <body> tag as a content holder. ajaxWrapper is the object simulating the request and dataMockup is an array containing our users. Here is the function that we will use:

    [js]
    var displayUsers = function(domEl, ajax) {
    ajax.get(‘/api/users’, function(users) {
    var html = ”;
    for(var i=0; i < users.length; i++) {
    html += '

    ‘ + users[i] + ”;
    }
    domEl.innerHTML = html;
    });
    }
    [/js]

    And of course, if we run displayUsers(body, ajaxWrapper) we will see the three names displayed on the page and /api/users requested in our console. We could say that our method has two dependencies – body and ajaxWrapper. So, now the idea is to make the function working without passing arguments, i.e. we have to get the same result by calling just displayUsers(). If we do that with the code so far the result will be:

    [js]
    Uncaught TypeError: Cannot read property ‘get’ of undefined
    [/js]