project.js initialization function
Opened this issue · 4 comments
https://github.com/CU-CommunityApps/cwd_project/blob/main/js/project.js
Let's change how project.js
is initialized -- follow-up to discussion on Slack.
Specifically:
- Use Drupal 8/9 best practices
- Er, well now it's Drupal 10!...
- (Probably?) Include
'use strict';
with whatever we come up with.
To do
- Decide how to init
project.js
- Update
project.js
- Update cwd_project on CD Demo (manually)
- (Optionally) Publish cwd_project release with this change
Background
Drupal reference
Best practices laid out in Drupal JavaScript API documentation
What's in project.js now
(https://github.com/CU-CommunityApps/cwd_project/blob/main/js/project.js)
jQuery(document).ready(function($) {
// By default, site search uses this site.
$('input[type=radio][name=sitesearch]').on('change', function() {
switch ($(this).val()) {
// ...etc etc etc...
}
});
});
What's in some of our D8 sites' child theme JS files
(probably based on the old cwd_ssit theme?? -- but I haven't confirmed this speculation)
(function ($, Drupal) {
'use strict';
// By default, site search uses this site.
$('input[type=radio][name=sitesearch]').on('change', function() {
switch ($(this).val()) {
// ...etc etc etc...
}
});
})(jQuery, this);
(PLEASE UPDATE THE ISSUE TITLE IF I'M USING THE WRONG TERMINOLOGY!!)
@melissagore You've spent some time on Drupal JS things recently... Do you think this issue is still relevant? Or, maybe kinda relevant but would be better as a fresh issue? Or no longer relevant?
I think this issue is still relevant. I reviewed the slack conversation that launched the issue. These are the highlights.
- Add
'use strict';
- It's likely any JS added to the file will need a ready event
- This is not part of the CSS framework so we can and should use Drupal specific JS
- For Drupal specific JS follow Drupal JavaScript API docs
This is how we'd add 'use strict';
to the option with the document ready function:
(function ($) {
'use strict';
$( document ).ready( function () {
// project specific js
})
})(jQuery);
This is the more Drupal way, replacing the document ready function with Drupal behaviors:
(function ($, Drupal) {
'use strict';
Drupal.behaviors.cwd_project = {
attach: function (context, settings) {
// project specific js
}
};
})(jQuery, Drupal);
In looking at the Drupal JS docs, we may want to add core/once
to the Drupal behaviors option too. @inaydich I notice you use once in Experience JS. Do you think we should add once here too? I don't have a lot of experience using behaviors nor once. I do know, if we add once, it has to be core/once
because jquery/once
is deprecated and removed from D10.
Thank you so much for the thorough review + analysis + recs, Melissa 🙌
I added this issue to the "Monday/D&D" issue review queue (i.e. full team) -- also great if Irina has time to reply in the meantime (we can always drop it from the review queue).