InteractsWithRenderApi.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Dcat\Admin\Traits;
  3. use Dcat\Admin\Contracts\LazyRenderable;
  4. /**
  5. * @property string $target
  6. */
  7. trait InteractsWithRenderApi
  8. {
  9. /**
  10. * @var LazyRenderable
  11. */
  12. protected $renderable;
  13. /**
  14. * @var string
  15. */
  16. protected $loadScript;
  17. /**
  18. * 监听异步渲染完成事件.
  19. *
  20. * @param string $script
  21. *
  22. * @return $this
  23. */
  24. public function onLoad(string $script)
  25. {
  26. $this->loadScript .= ";{$script}";
  27. return $this;
  28. }
  29. public function getRenderable()
  30. {
  31. return $this->renderable;
  32. }
  33. public function setRenderable(?LazyRenderable $renderable)
  34. {
  35. $this->renderable = $renderable;
  36. return $this;
  37. }
  38. protected function getRenderableScript()
  39. {
  40. if (! $this->getRenderable()) {
  41. return;
  42. }
  43. $url = $this->renderable->getUrl();
  44. return <<<JS
  45. target.on('{$this->target}:load', function () {
  46. Dcat.helpers.asyncRender('{$url}', function (html) {
  47. body.html(html);
  48. {$this->loadScript}
  49. target.trigger('{$this->target}:loaded');
  50. });
  51. });
  52. JS;
  53. }
  54. }