B
B
Brees2019-08-01 00:10:20
JavaScript
Brees, 2019-08-01 00:10:20

How to write good javascript for Bitrix component?

There is a component with complex js logic that can be embedded on the page via ajax, it is necessary to initialize the handlers, etc., the first thing that comes to mind is to write something like this:

class ShopSection {
  constructor(id) {
    this.elem = document.getElementById(id);
    ...
  }
  initMap() {
    ...
  }
}

But here the question is how to get a link (id or class) to our component (for example, a common div wrapper) from this script so that several components on the page work correctly and do not interfere with each other?
Is it possible to generate a unique component id that can be simply passed:
<div id="<?php echo %UNIQUE_ID% ?>">
...
</div>
<script>
new ShopSection(<?php echo %UNIQUE_ID% ?>);
</script>

Or is this a bad idea? How do you act in such situations and in what style do you write your js for Bitrix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Shevchenko, 2019-08-02
@brees

That's pretty much how it's done. In the bitrix:catalog.section component with a list of products, a unique ID for the product is generated as follows:

$uniqueId = $item['ID'].'_'.md5($this->randString().$component->getAction());
//$item['ID'] - ID товара
//$this->randString() - рандомная строка
//$component->getAction() - по документации "Метод возвращает название текущего действия."

//Ниже пример подключения JS к списку товаров
$obName = 'ob'.preg_replace('/[^a-zA-Z0-9_]/', 'x', $this->GetEditAreaId($navParams['NavNum'])); //название переменной в которой, помещен JS-объект с логикой компонента.

//Ну и создание объекта в который передаются параметры.
var <?=$obName?> = new JCCatalogSectionComponent({
    siteId: '<?=CUtil::JSEscape($component->getSiteId())?>',
    componentPath: '<?=CUtil::JSEscape($componentPath)?>',
    navParams: <?=CUtil::PhpToJSObject($navParams)?>,
    deferredLoad: false, // enable it for deferred load
    initiallyShowHeader: '<?=!empty($arResult['ITEM_ROWS'])?>',
    bigData: <?=CUtil::PhpToJSObject($arResult['BIG_DATA'])?>,
    lazyLoad: !!'<?=$showLazyLoad?>',
    loadOnScroll: !!'<?=($arParams['LOAD_ON_SCROLL'] === 'Y')?>',
    template: '<?=CUtil::JSEscape($signedTemplate)?>',
    ajaxId: '<?=CUtil::JSEscape($arParams['AJAX_ID'])?>',
    parameters: '<?=CUtil::JSEscape($signedParams)?>',
    container: '<?=$containerName?>'
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question