Created
April 9, 2024 15:21
-
-
Save joetannenbaum/bcdcd36e73bf0c247497d448f4eace33 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Livewire\Attributes; | |
use Attribute; | |
use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; | |
use function Livewire\store; | |
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)] | |
class SyncTabs extends LivewireAttribute | |
{ | |
public function mount() | |
{ | |
$listeners = store($this->component)->get( | |
'listenersFromAttributes', | |
[], | |
); | |
$jsFireEvent = collect($listeners)->map(function ($handler, $event) { | |
return <<<JS | |
\$wire.on('{$event}', (params) => { | |
window.bc.postMessage({name: '{$event}', params: params[0]}); | |
}); | |
JS; | |
})->implode("\n"); | |
$jsOnEvent = collect($listeners)->map(function ($handler, $event) { | |
return <<<JS | |
window.bc.onmessage = (event) => { | |
if (event.data.name === '{$event}') { | |
\$wire.call('{$handler}', event.data.params); | |
} | |
}; | |
JS; | |
})->implode("\n"); | |
$this->component->js(<<<JS | |
window.bc = new BroadcastChannel("{$this->component->getName()}"); | |
{$jsFireEvent} | |
{$jsOnEvent} | |
JS); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment