I created a custom theme (a sub-theme of Radix base theme).
I am loading a custom Javascript file (radix_sub.script.js
) using the module libraries.yaml
file like below:
style:
version: VERSION
css:
theme:
assets/css/radix_sub.style.css: {}
js:
'//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js': { type: external }
'//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js': { type: external }
assets/js/radix_sub.script.js: {}
dependencies:
- core/drupal
- core/jquery
- core/jquery.once
- core/drupalSettings
In that file, I want to register some JavaScript events (Bootstrap modal).
(function ($, Drupal) {
Drupal.behaviors.portfolio = {
attach: function (context) {
console.log('CONTEXT', context);
$('#portfolioModal', context).once('bootstrap-modal-shown', console.log('*** REGISTER SHOWN.BS.MODAL')).each(function () {
$(this).on('shown.bs.modal', function () {
console.log('SHOWN BS MODAL EVENT TRIGGERED');
});
});
$('#portfolioModal', context).once('bootstrap-modal-hidden', console.log('*** REGISTER HIDDEN.BS.MODAL')).each(function () {
$(this).on('hidden.bs.modal', function () {
console.log('HIDDEN BS MODAL EVENT TRIGGERED');
});
});
}
}
}(jQuery, Drupal));
It works. I see both SHOWN BS MODAL EVENT TRIGGERED and HIDDEN BS MODAL EVENT TRIGGERED logs when I show/hide the modal.
First, am I doing that the correct way?
This is what my developer console looks like when I load my page.
This happens only when I am logged in (as admin). When I am anon, I see the REGISTER logs only once but here my code seems to be executed 11 times.
Is this normal behavior? And/or why is it doing that?
Is this normal behavior?
prob not, can you replicate on fresh D8 install with Bartik theme?console.log()
s. jQueryonce()
is called on page load and on any AJAX load. All the scripts that can be seen in the screenshot (plainTextEditor.js
,image.js
,theme.js
, etc.) are loaded on the page via AJAX, hence the 10 subsequent logs after the initial page load. The code within thejQuery.each()
callbacks is executed only once.