Skip to content

Instantly share code, notes, and snippets.

@joetannenbaum
Created April 9, 2024 15:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joetannenbaum/bcdcd36e73bf0c247497d448f4eace33 to your computer and use it in GitHub Desktop.
Save joetannenbaum/bcdcd36e73bf0c247497d448f4eace33 to your computer and use it in GitHub Desktop.
<?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