block editor - Interactivity API using withScope

admin2025-05-31  6

I'm attempting to use the interactivity API for the first time. It seems to require using withScope in order to get some context from form filters. I can test individual pieces of my code and they work, but anything within withScope does not seem to run at all, even if I dumb down the code as much as possible There are no console errors, the file loads and the other pieces of it run. I read something that was over my head about withScope potentially not working in an async context.

block.json

    "$schema": ".json",
    "apiVersion": 3,
    "title": "Custom Post Filters",
    "description": "Display custom posts based on selected filters.",
    "textdomain": "namespace",
    "name": "namespace/post-filters",
    "icon": "filter",
    "category": "custom",
    "attributes": {
        "filterType": {
            "type": "string",
            "default": ""
        },
        "selectedPosts": {
            "type": "array",
            "default": []
        }
    },
    "supports": {
        "html": false,
        "interactivity": {
            "interactive": true
        }
    },
    "editorScript": "file:./index.js",
    "style": "file:./style.css",
    "viewScriptModule": "file:./view.js",
    "render": "file:./markup.php"
}

markup.php

<div
    class="filtered-posts post-list-container"
    data-wp-interactive="namespace/post-filter"
    data-wp-context="<?php echo esc_attr( wp_json_encode( [ 'filterId' => (int) $filter['id'] ] ) ); ?>"
>
    <button data-wp-on--click="actions.testScope">Test withScope</button>
</div>

view.js

import { store, withScope } from '@wordpress/interactivity';

store('namespace/post-filter', {
    actions: {
        testScope() {
            const el = getElement(); 
            console.log('Captured element:', el);

            if (!el) {
                return;
            }

            console.log('
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748642806a313728.html

最新回复(0)