Skip to content

Instantly share code, notes, and snippets.

@sirreal
Last active January 24, 2024 15:03
Show Gist options
  • Save sirreal/346b46f61396a47c040f487a7940bf80 to your computer and use it in GitHub Desktop.
Save sirreal/346b46f61396a47c040f487a7940bf80 to your computer and use it in GitHub Desktop.
Demo of viewScriptModule
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"title": "Jon's cool counter",
"name": "jon/the-block",
"editorScript": "file:./index.js",
"viewScriptModule": "file:./view.js",
"render": "file:./render.php",
"category": "text"
}
<?php return array('dependencies' => array('react', 'wp-blocks'), 'version' => '36efaf9a0f26eb9312c9');
(()=>{"use strict";const e=window.React,t=window.wp.blocks,o=JSON.parse('{"$schema":"https://schemas.wp.org/trunk/block.json","apiVersion":3,"title":"Jon\'s cool counter","name":"jon/the-block","editorScript":"file:./index.ts","viewModule":"file:./view.mts","render":"file:./render.php","category":"text"}');t.registerBlockType(o,{edit:()=>(0,e.createElement)("div",null,"counter"),save:()=>(0,e.createElement)("div",null,"counter")})})();
<?php
/*
* Plugin Name: A counter
*/
add_action(
'init',
function () {
register_block_type_from_metadata(__DIR__ . '/block.json');
}
);
<div data-wp-interactive='{"namespace":"jon/the-block"}' data-wp-context='{"val":0}'>
<input readonly type='number' class='jon-val' data-wp-bind--value='context.val' value='0' />
<button class='jon-inc' data-wp-on--click='actions.inc'>+</button>
<button class='jon-dec' data-wp-on--click='actions.dec'>-</button>
</div>
<?php return array('dependencies' => array(), 'version' => '75dbd483e746933f689a', 'type' => 'module');
function e(e){e.preventDefault(),e.target.parentElement.querySelector(".jon-val").value--}function t(e){e.preventDefault(),e.target.parentElement.querySelector(".jon-val").value++}function n(){[...document.querySelectorAll(".jon-inc")].forEach((e=>e.addEventListener("click",t))),[...document.querySelectorAll(".jon-dec")].forEach((t=>t.addEventListener("click",e)))}"loading"!==document.readyState?n():document.addEventListener("DOMContentLoaded",n);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment