What is the «data-role» attribute in the HTML templates for?

template
data-role

(Poongudivanan N) #1

Hello

I saw some of the code like below from admin end…
So data-role=“visibility-trigger” what KO js actually doing… here…

<div class="admin__field admin__field-option">
                            <input type="checkbox"
                                   id="hide-from-product-page"
                                   data-role="visibility-trigger"
                                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"
                                   value="1"
                                   class="admin__control-checkbox"
                                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][disabled]"
                            <% if (data.disabled == 1) { %>checked="checked"<% } %> />

                            <label for="hide-from-product-page" class="admin__field-label">
                                <?php /* @escapeNotVerified */ echo __('Hide from Photo Gallery Page')?>
                            </label>
                        </div>

Here also using data-role attr ?

<script data-role="img-dialog-container-tmpl" type="text/x-magento-template">
  <div class="image-panel" data-role="dialog">
  </div>
</script>

Here too

 <script data-role="img-dialog-tmpl" type="text/x-magento-template">
        <div class="image-panel-preview">
            <img src="<%- data.url %>" alt="<%- data.image_description %>" />
        </div>

(Dmitry Fedyuk) #2

Magento 2 sometimes uses the «data-*» attributes instead of CSS clases.

The motivation is well described (for another software product, not Magento) here:

Why data?
They could simply use role as an attribute (like other frameworks do), but this would make the resulting HTML invalid. Therefore an data- is added to every attribute name.

Why not classes?
I thing the main reasion for that is, to separate view from logic as far as it is possible. In larger projects CSS and JavaScript are not written by the same person.

stackoverflow.com/a/16409520