Skip to content

Magento 2 virtual elements vs data-bind

In which cases we should use ‘virtual elements’ and ‘data-bind’ ?

For example, this code using virtual elements:

<div class="custom-configs">
<h2><!-- ko i18n: 'Custom Settings' --><!-- /ko --></h2>
<!-- ko foreach: { data: customSettings, as: 'customSetting' } -->
<div>
    <!-- ko i18n: 'Setting' --><!-- /ko -->
    <!-- ko text: $index() + 1 --><!-- /ko -->:
    <!-- ko text: ko.toJSON(customSetting) --><!-- /ko -->:
</div>
<!-- /ko -->

and this code using ‘data-bind’ syntax:

<div class="custom-configs">
<h2 data-bind="i18n: 'Custom Settings'"></h2>
<div data-bind="foreach: { data: customSettings, as: 'customSetting' }">
    <div>
        <span data-bind="i18n: 'Setting'"></span>
        <span data-bind="text: $index() + 1"></span>
        <span data-bind="text: ko.toJSON(customSetting)"></span>
    </div>
</div>

Why knockoutjs use 2 approaches if both of them do the same. Please, share with me any thoughts in which cases it should be used ‘virtual elements’ and ‘data-bind’ syntax.

P.S. I noticed one difference with virtual elements, in some cases it’s not create extra html element. Is this the only one difference between them?