Building a frontend with ErgoJS


I am pleased to present to your attention a js framework called ErgoJS for creating rich web applications. And yes, I love bicycles.

In this article, I will not describe the framework itself in detail and touch only on general points, since I plan to soon post the relevant information on the project website.

Let's start the acquaintance.

I want to say right away that ErgoJS does not have a core idea, so to speak, of a special “killer feature” like MVC, MVVM, its own template language, etc.
ErgoJS was primarily created as a library of widgets, but now, as we grow older, the emphasis has shifted towards building full-fledged web applications.

Work on this framework began a long time ago, it was intended for programmers who are used to dealing with a "fat" client and riveting applications alone. But participation in the web development team, which was initially divided into three specializations: designer - layout designer - programmer, and later on a couple of designer-layout designer and programmer-designer made some corrections. It was easy and fun to create a programming tool, but somehow it didn’t work with styles and markup right away (hello and goodbye IE6). Long meetings with the team, attempts to “do it once and for all” did not bring noticeable results and only took up precious time. It was necessary to look for another solution. And this continued until the advent of CSS frameworks, which, although not completely, tidied up and systematized the magic of layout,

Targets and goals


Accumulation and fixation of methods, not decisions


ErgoJS consists of two parts: the kernel and the widget library. Although they are closely related, each has its own purpose. So the kernel tries to incorporate and systematize the techniques and working methods of the programmer and layout designer, allowing you to create and modify widgets that play the role of web application bricks. In the most degenerate case, using the kernel components, you can perform the usual page layout using the capabilities of the html namespace .

The widget library, in turn, contains a reference set of components from which the application is built. This changes the approach to development (we don’t “create”, but “assemble”) and reduces the requirements for the programmer’s level of training (it is not necessary to know how to align or center elements on the page - just use the necessary layout). The programmer can use the components included in the library to create a prototype, sometimes rough, sometimes quite accurate, to further “finish” it to the level of a finished software product.

Principle of least surprise


The functions and behavior of the components of the framework tend to have obvious and predictable behavior. This is difficult to achieve, because different people have different experiences and views on how certain things should work, but discussing the issue with a group of specialists can solve many problems.

Don't do too much


If something can be implemented using HTML or CSS, then this should be done. Using JavaScript allows you to compensate for the lack of full standards support by popular browsers (polyfills) or add new features that did not fall under standardization.
When the specifications are updated, the ErgoJS functionality is updated, for example, the expected support of flexbox layouts by all browsers will allow us to abandon a significant part of the ErgoJS layout functionality, which concerns the automatic calculation of widget sizes.

Compact code


General solution of problems always has one drawback - redundancy. In this case, there should be either a refusal to generalize, or the creation of a mechanism for a brief record of operations. ErgoJS strives to follow the second path, but with one rule: "if the code is written for reuse, then general forms should be used." In all other cases, short forms are preferable.

Features of ErgoJS


Declarative programming style.


When a task is set for a programmer, he searches for a solution algorithm and implements it. With the user interface, everything is different - the solution does not imply an algorithm, but allows a structural decomposition. In this case, you can split the picture into small parts and solve each of them individually, one after another. But what happens if all these parts already have their own solutions and the developer needs to assemble them together, how do builders assemble and build a house from panels or bricks? The very nature of the development is changing - one does not have to think about how to lay a brick one after the other, but about how to connect panels together, where to make openings, how to install overlappings. To understand what is at stake, consider a couple of examples.

Create a box with buttons imperatively:

var box = new Ergo.widgets.Box();
var btn1 = new Ergo.widgets.Button({text: 'Кнопка 1'});
var btn2 = new Ergo.widgets.Button({text: 'Кнопка 2'});
var btn3 = new Ergo.widgets.Button({text: 'Кнопка 3'});
box.items.add(btn1);
box.items.add(btn2);
box.items.add(btn3);

And declaratively:

var box = $.ergo({
  etype: 'box',
  defaultItem: {
    etype: 'button'
  },
  items: [
    {text: 'Кнопка 1'},
    {text: 'Кнопка 2'},
    {text: 'Кнопка 3'}
  ]
});

This example shows that with an imperative approach, we ourselves consistently create a widget, and with a declarative one, we indicate to a certain “performer” the required result so that he does everything for us. Naturally, the more accurate and understandable we describe the result, the better it will coincide with our plan.

In a sense, ErgoJS forces you to perform minimal interface design and only then begin to create it.

Virtual Widget Tree and DOM


Widgets are independent entities, or rather, a hierarchy of entities for which the DOM is just a representation. This means that although each widget is associated with a specific DOM element, when displayed, the number, location and relationships between elements do not necessarily correspond to those in VWT.

VWT is very similar to the Shadow DOM, but if the second is a mixture of logic and presentation, then VWT is pure logic. This means that VWT can use the Shadow DOM to optimize the rendering process, but is not its counterpart.

// создадим виджет-кнопку
$.ergo({
    etype: 'button',
    components: {
        icon: {
            etype: 'icon',
            // сделаем, чтобы иконка отображалась до текста
            weight: -10,
            // виджет создается, но не добавляется в DOM (это можно сделать позже)
            autoRender: false
        },
        content: {
            // оставим содержимое простым текстом
            etype: '&text'
        }
    }
});

Hierarchical Data Binding


In most cases, the data structure corresponds to the structure of the page elements, which, however, is not surprising, since the data is logically connected within the framework of the domain model, and their display retains this logic, since it is by definition known and understandable to the user.

By connecting data to a widget, it is automatically bound to all child widgets. The binding process can be controlled by disabling or ignoring the binding for both individual widgets in VWT and subtrees.

var obj = {
    title: 'Тест',
    datetime: '2014-11-10T12:55:00',
    description: 'Loremipsum',
    img: 'img/image_001.jpg'
};
$.ergo({
    etype: 'box',
    // привязываем данные при создании виджета
    data: obj,
    // компоненты
    components: {
        header: {
            binding: 'text',
            dataId: 'title'
        },
        content: {
            // расположим элементы вертикально
            layout: 'stack',
            items: [{
                etype: 'html:img',
                // связываем данные с опцей src
                binding: 'src'
            }, {
                binding: 'text'
                dataId: 'description'
            }, {
                dataId: 'datetime',
                // связывание можно настроить на свое усмотрение
                binding: function(v) {
                    this.opt('text', moment(v).format('YYYY-MM-DD'));
                }
            }]
        }
    }
});

Dynamic Data Binding


The binding mechanism implies the influence of data on the parameters, appearance, state of the widget. With dynamic linking, the data determines the structure of the VWT widgets, and the data connection with the widgets is one-way, i.e. changing the view does not affect the data, but changing the data rearranges the relationships between widgets.

var list_data = ['Африка', 'Европа', 'Антарктида', 'Азия']
$.ergo({
    // создаем список UL/LI
    etype: 'html:ul',
    // определим элемент по умолчанию
    defaultItem: {
        etype: 'html:li',
        // данные свяжем с опцией text
        binding: 'text'
    },
    // указываем, что элементы виджета управляются данными
    dynamic: true,
    // связываем данные с виджетом
    data: list_data
});

In addition to the explicit purpose of dynamic linking for managing flat lists and tree-like lists, there is also an implicit - access control for the user. That is, you can change the page display not only by loading different scripts for different rights, but also by sharing the data that the server sends.

Separation into components and elements


In fact, this separation is determined by javascript itself. It has two types of collections: Array and Object - a simple array and associative. Therefore, child widgets that have a unique name become components (`components`), and those that have a pin number become elements (` items`).

// кнопка с пиктограммой
$.ergo({
    etype: 'button',
    components: {
        // компонент-пиктограмма `icon`
        icon: {
            etype: 'icon',
            state: 'fa-cog'
        },
        // текстовый компонент `content`
        content: {
            etype: '&text'
        }
    },
    text: 'Тестовая кнопка'
});
// список
$.ergo({
    etype: 'html:ul',
    defaultItem: {
        etype: 'html:li',
    },
    items: ['Item_1', 'Item_2', 'Item_3']
});

Popular framework as a basis (jQuery)


ErgoJS itself uses only a small part of jQuery's capabilities, and as it develops, it switches to VanillaJS in performance-critical areas. However, in practice, jQuery greatly simplifies the work of creating impurities and opens the way for connecting a huge number of third-party plug-ins.

// создаем виджет-список
var w = $.ergo({
    etype: 'list',
    items: ['Яблоко', 'Апельсин', 'Груша']
});
// jQuery-элемент 
    доступен через свойство el w.el.css('color', '#f00');

other...


The best way to understand what ErgoJS is all about is to familiarize yourself with the examples on the site .

Pros and cons


The good points of ErgoJS include:

  1. "Pure" HTML, no "extra" attributes
  2. JavaScript developed application
  3. One basic object - a widget


And also mention the disadvantages:

  1. Relatively low rendering speed
  2. There are few ready-made solutions, while there is no way to work in design mode
  3. No specialized test support

Also popular now: