How to execute some javascript code in the editor when a block pattern is added?

I want to know if there’s a way to use subscribe so that when a
pattern is added I can run something

It’d be easy to do that if we had something like getPatterns() which would behave similar to getBlocks(), and/or if an inserted pattern (which could contain one or more blocks) had a comment delimiter like <!-- wp:pattern {"title":"My Pattern"} -->, which then allows us to easily compare the current patterns with the previous ones by subscribing to changes in the post content.

But since we don’t have any of that (yet?), then maybe an old-school way would work for you..

jQuery( document ).on( 'click', '.block-editor-block-patterns-list__item', function () {
    const title = jQuery( this ).attr( 'aria-label' ) || 'Untitled';
    // Sorry, I could not find a way to find the pattern's slug (which is unique).

    console.log( `pattern "${ title }" selected and maybe inserted` );
    // do your something here
} );

That is of course not (very) reliable, since the element (e.g. its class name) could change in future releases or even in the current one, e.g. modified via a plugin. However, the above code did work fine with the block pattern inserter.

Additionally, in WordPress v6.2.2, you can use wp.data.select( 'core' ).getBlockPatterns() to get the list of available patterns, and maybe do something like so in the above click event handler:

const patterns       = wp.data.select( 'core' ).getBlockPatterns()
    .filter( args => title === args.title );
const patternContent = patterns?.[0]?.content; // Use the first matched pattern.

If you know the pattern slug (i.e. the pattern’s name value), e.g. core/three-columns-of-text, then you can use wp.data.select( 'core/block-editor' ).__experimentalGetParsedPattern() to get the pattern object.

const patternObj     = wp.data.select( 'core/block-editor' ).__experimentalGetParsedPattern( 'core/three-columns-of-text' );
const patternContent = patternObj?.content;

Last but not least, a second possible way is by checking if there’s a notice which says Block pattern "<title>" inserted., i.e. subscribing to the changes in the notices, but you would need to write the code on your own — see getNotices().

deneme bonusudeneme bonusu veren sitelerpulibet girişOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino