6

I've loaded a jQuery script with enqueue_block_editor_assets for gutenberg and wp_print_scripts for frontend which is loaded fine.

add_action( 'wp_print_scripts', 'sk_load_script' );
add_action( 'enqueue_block_editor_assets', 'sk_load_script' );
add_action( 'enqueue_block_editor_assets', 'sk_gutenberg_script' );

The sk_load_script function loads both the frontend.js for both frontend and gutenberg whereas sk_gutenberg_script function loads block.js

However when I do in frontend.js:

jQuery(document).ready(function ($) {
    var place = jQuery('.sk-place');
    console.log(place);
}

That does not print anything on the console in the Gutenberg area. But it prints in the frontend.

In the block.js edit function, I have the custom event.

constructor() {
    const event = new Event( 'skLoad' );
    document.dispatchEvent( event );
}

With that, when I do in frontend.js,

document.addEventListener( 'skLoad', function( e ) {
     var place = jQuery('.sk-place');
    console.log(place);
}, false );

This runs fine as well, but only while adding the block.

How do I run that when the already preset block is in place on loading Gutenberg area, or when loading the block (not on edit only)?

Actually, I also need that on change of other inputs in the Gutenberg block settings, I mean in the edit() in block.js such as on change of this: https://ibb.co/SXkbhc6

Thanks!

5
  • This might help github.com/WordPress/gutenberg/issues/… Jan 12, 2021 at 7:34
  • 1
    Put your sk_load_script and sk_gutenberg_script in here. Jan 21, 2021 at 17:43
  • Are your scripts supposed to load for all blocks? Because you should register them with a specific block otherwise. Jan 21, 2021 at 17:44
  • What are you trying to accomplish with the code that you would like to execute "when the Block Editor loads?" There are many entry points to Block Editor functionality, and a lot of them are specifically tailored for various purposes - there may well be one far more suited to your needs than a generic "load" event. Similarly, what do you want to do externally when the block's settings change that can't already be done in the edit() component?
    – bosco
    Jun 17, 2021 at 4:52
  • 1
    note that in gutenberg the DOM elements/tags on the page are managed by React and could be destroyed and recreated at any time, so be careful about modifying them with jQuery, especially if you're storing data in those tags as they may be lost. WordPress/the block editor itself uses WP Data to store things then uses that data to create user interface. What you're trying to do is also unclear, any context as to the actual problem you're trying to face will help, as the answer to this question may not be the solution you hoped it to be.
    – Tom J Nowell
    Jun 17, 2021 at 10:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.