moonshine-software / moonshine

Laravel Admin panel and more. Simple for beginners and powerful for experts. Using Blade, Alpine.js and Tailwind CSS.
https://moonshine-laravel.com
MIT License
797 stars 104 forks source link

[3.x] Async callback refactoring #1313

Closed dev-lnk closed 1 month ago

dev-lnk commented 1 month ago

Refactoring AsyncCallback

FormBuilder::make(route('form.async'))->fields([
    Text::make('Name')
])
    ->async(
        callback: AsyncCallback::with(
            beforeRequest: 'myBeforeRequest',
            responseHandler: 'myResponseHandler',
            //Called after standard response processing if responseHandler is not specified
            afterResponse: 'myAfterResponse'
        )
),
document.addEventListener("moonshine:init", () => {
    MoonShine.onCallback('myBeforeRequest', function(form, component) {
        console.log('myBeforeRequest', form, component)
    })

    MoonShine.onCallback('myResponseHandler', function(data, form, events, alpineComponent) {
        console.log('myResponseHandler', data, form, events, alpineComponent)
    })

    // Called after standard response processing if responseHandleris not specified
    MoonShine.onCallback('myAfterResponse', function(data, messageType) {
        console.log('myAfterResponse', data, messageType)
    })
})

Now the fragment has access to events and all the capabilities of AsyncCallback

Fragment::make([
    FlexibleRender::make('<p> Test: ' . time() . '</p>')
])
    ->updateWith(
        events: [
            AlpineJs::event(JsEvent::FRAGMENT_UPDATED, 'fg-step-2'),
        ],
        callback: AsyncCallback::with(afterResponse: 'fgAfter')
    )
    ->name('fg-step-1')
,
//...
ActionButton::make('FG')
    ->dispatchEvent([AlpineJs::event(JsEvent::FRAGMENT_UPDATED, 'fg-step-1')])
,
MoonShine.onCallback('fgAfter', function(data, messageType) {
    console.log('fgAfter', data, messageType)
})