瀏覽代碼

异步组件重构,使用Dcat.init

jqh 4 年之前
父節點
當前提交
35a725699f

+ 7 - 4
resources/assets/dcat/js/Dcat.js

@@ -104,7 +104,7 @@ export default class Dcat {
      * @param callback
      * @param options
      */
-    initialize(selector, callback, options) {
+    init(selector, callback, options) {
         if (initialized[selector]) {
             initialized[selector].takeRecords();
             initialized[selector].disconnect();
@@ -121,9 +121,12 @@ export default class Dcat {
                 }
                 $this.addClass('initialized');
 
-                // 生成随机ID
-                var id = "_"+self.helpers.random();
-                $this.attr('id', id);
+                // 如果没有ID,则自动生成
+                var id = $this.attr('id');
+                if (! id) {
+                    id = "_"+self.helpers.random();
+                    $this.attr('id', id);
+                }
 
                 callback.call(this, $(this), id)
             }, options);

+ 38 - 23
resources/views/widgets/dialogtable.blade.php

@@ -1,7 +1,7 @@
-<span>
-    <span style="cursor: pointer" id="button-{{ $id }}">{!! $button !!}</span>
+<span class="{{ $class }}">
+    <span style="cursor: pointer" class="switch-dialog">{!! $button !!}</span>
 
-    <template id="temp-{{ $id }}">
+    <template>
         <div {!! $attributes !!}>
             <div class="p-2 dialog-body">{!! $table !!}</div>
 
@@ -12,18 +12,18 @@
     </template>
 </span>
 
-<script>
-    var id = replaceNestedFormIndex('{{ $id }}'),
-        area = screen.width <= 850 ? ['100%', '100%',] : '{{ $width }}',
+<script init=".{{ $class }}">
+    var area = screen.width <= 850 ? ['100%', '100%',] : '{{ $width }}',
         offset = screen.width <= 850 ? 0 : '70px',
-        _id, _tempId, _btnId, _tb;
+        _tb = '.async-table', _container = '.dialog-table',
+        _id, _temp, _btnId;
 
     setId(id);
 
     function hidden(index) {
         {!! $events['hidden'] !!}
 
-        $(_id).trigger('dialog:hidden');
+        getLayer(index).find(_container).trigger('dialog:hidden');
     }
 
     function open(btn) {
@@ -34,28 +34,32 @@
             offset: offset,
             maxmin: false,
             resize: false,
-            content: $(_tempId).html(),
+            content: $(_temp).html(),
             success: function(layero, index) {
-                $(_id).attr('layer', index);
+                var $c = getLayer(index).find(_container),
+                    $t = getLayer(index).find(_tb);
 
-                setDataId($(_id));
+                $c.attr('layer', index);
+
+                setDataId($c);
+                setMaxHeight(index);
 
                 {!! $events['shown'] !!}
 
                 @if(!empty($events['load']))
-                    $(_tb).on('table:loaded', function (event) { {!! $events['load'] !!} });
+                $t.on('table:loaded', function (event) { {!! $events['load'] !!} });
                 @endif
 
                 setTimeout(function () {
-                    Dcat.grid.AsyncTable({container: _tb});
+                    Dcat.grid.AsyncTable({container: $t});
 
-                    $(_tb).trigger('table:load');
+                    $t.trigger('table:load');
                 }, 100);
 
-                $(_id).trigger('dialog:shown');
+                $c.trigger('dialog:shown');
 
-                $(_id).on('dialog:open', openDialog);
-                $(_id).on('dialog:close', closeDialog)
+                $c.on('dialog:open', openDialog);
+                $c.on('dialog:close', closeDialog)
             },
             cancel: function (index) {
                 btn && btn.removeAttr('layer');
@@ -76,11 +80,9 @@
     function setId(val) {
         if (! val) return;
 
-        id = val;
-        _id = '#'+id;
-        _tempId = '#temp-'+id;
-        _btnId = '#button-'+id;
-        _tb = _id+' .async-table';
+        _id = '#' + val;
+        _temp = _id + ' template';
+        _btnId = _id + ' .switch-dialog';
     }
 
     function openDialog () {
@@ -92,10 +94,14 @@
         }
     }
 
+    function getLayer(index) {
+        return $('#layui-layer'+index)
+    }
+
     function closeDialog() {
         var index = $(this).attr('layer');
 
-        $(_id).removeAttr('layer');
+        getLayer(index).find(_container).removeAttr('layer');
         $(_btnId).removeAttr('layer');
 
         if (index) {
@@ -104,5 +110,14 @@
         }
     }
 
+    function setMaxHeight(index) {
+        var maxHeight = ($(window).height() - 250);
+        if (maxHeight < 250) {
+            maxHeight = maxHeight + 120;
+        }
+
+        getLayer(index).find('.layui-layer-content').css({'max-height': maxHeight});
+    }
+
     $(_btnId).on('click', openDialog);
 </script>

+ 1 - 1
src/Traits/HasHtml.php

@@ -121,7 +121,7 @@ trait HasHtml
             }
 
             if ($init = $element->getAttribute('init')) {
-                $script = "Dcat.initialize('{$init}', function (\$this, id) { {$script}\n });";
+                $script = "Dcat.init('{$init}', function (\$this, id) { {$script}\n });";
             } else {
                 $script = "(function () {{$script}\n})();";
             }

+ 2 - 1
src/Widgets/DialogTable.php

@@ -51,8 +51,9 @@ class DialogTable extends Widget
         $this->title($title);
         $this->from($table);
 
+        $this->elementClass = 'dialog-table-container';
+
         $this->class('dialog-table');
-        $this->id('dialog-table-'.Str::random(8));
     }
 
     /**

+ 4 - 15
src/Widgets/Lazy.php

@@ -18,8 +18,7 @@ class Lazy extends Widget
         $this->setRenderable($renderable);
         $this->load($load);
 
-        $this->class('lazy-box');
-        $this->id('lazy-'.Str::random(8));
+        $this->class($this->elementClass = 'lazy-box');
     }
 
     /**
@@ -36,29 +35,19 @@ class Lazy extends Widget
         return $this;
     }
 
-    /**
-     * 获取触发异步渲染JS代码.
-     *
-     * @return string
-     */
-    public function getLoadScript()
-    {
-        return "$('{$this->getElementSelector()}').trigger('{$this->target}:load');";
-    }
-
     protected function addScript()
     {
         $loader = $this->load ? "target.trigger('{$this->target}:load')" : '';
 
         $this->script = <<<JS
-(function () {
-    var target = $('{$this->getElementSelector()}'), body = target;
+Dcat.init('{$this->getElementSelector()}', function (target) {
+    var body = target;
     {$this->getRenderableScript()}
 
     body.html('<div style="min-height:150px"></div>').loading();
     
     {$loader}
-})();
+});
 JS;
     }
 

+ 8 - 8
src/Widgets/LazyTable.php

@@ -3,7 +3,6 @@
 namespace Dcat\Admin\Widgets;
 
 use Dcat\Admin\Grid\LazyRenderable;
-use Illuminate\Support\Str;
 
 class LazyTable extends Widget
 {
@@ -41,8 +40,7 @@ class LazyTable extends Widget
         $this->from($renderable);
         $this->load($load);
 
-        $this->class('async-table');
-        $this->id('async-table-'.Str::random(8));
+        $this->class($this->elementClass = 'async-table');
     }
 
     /**
@@ -100,7 +98,7 @@ class LazyTable extends Widget
      */
     public function onLoad(string $script)
     {
-        $this->script .= "$('{$this->getElementSelector()}').on('table:loaded', function (event) { {$script} });";
+        $this->script .= "\$this.on('table:loaded', function (event) { {$script} });";
 
         return $this;
     }
@@ -110,18 +108,20 @@ class LazyTable extends Widget
         $loader = $this->load ? $this->getLoadScript() : '';
 
         $this->script = <<<JS
-Dcat.grid.AsyncTable({container: '{$this->getElementSelector()}'});
-{$loader}
+Dcat.init('{$this->getElementSelector()}', function (\$this) {
+    Dcat.grid.AsyncTable({container: \$this});
+    {$loader}
+});
 JS;
     }
 
     /**
      * @return string
      */
-    public function getLoadScript()
+    protected function getLoadScript()
     {
         return <<<JS
-$('{$this->getElementSelector()}').trigger('table:load');
+\$this.trigger('table:load');
 JS;
     }
 

+ 2 - 2
src/Widgets/Modal.php

@@ -174,7 +174,7 @@ class Modal extends Widget
                 ->simple()
                 ->load(false);
 
-            $this->onShow($table->getLoadScript());
+            $this->onShow("target.find('{$table->getElementSelector()}').trigger('table:load')");
         }
 
         if ($content instanceof LazyRenderable) {
@@ -303,7 +303,7 @@ class Modal extends Widget
 
         $this->script = <<<JS
 (function () {
-    var target = $('{$this->getElementSelector()}'), body = target.find('.modal-body');
+    var target = $('#{$this->id()}'), body = target.find('.modal-body');
     {$this->getRenderableScript()}
     {$script}
 })();

+ 16 - 1
src/Widgets/Widget.php

@@ -48,6 +48,11 @@ abstract class Widget implements Renderable
      */
     protected $options = [];
 
+    /**
+     * @var string
+     */
+    protected $elementClass;
+
     /**
      * @var bool
      */
@@ -120,6 +125,8 @@ abstract class Widget implements Renderable
         return [
             'attributes' => $this->formatHtmlAttributes(),
             'options'    => $this->options,
+            'class'      => $this->getElementClass(),
+            'selector'   => $this->getElementSelector(),
         ];
     }
 
@@ -173,7 +180,15 @@ abstract class Widget implements Renderable
      */
     public function getElementSelector()
     {
-        return '#'.$this->id();
+        return '.'.$this->getElementClass();
+    }
+
+    /**
+     * @return mixed
+     */
+    public function getElementClass()
+    {
+        return $this->elementClass ?: str_replace('\\', '_', static::class);
     }
 
     /**