Laravel中如何使用Event绑定值并借助Pusher更新对应div的时间?
Laravel + Pusher 实现div时间自动更新方案
1. 调整Event事件类
需要将div标识和对应时间都放入广播数据,修改TimeUpdated类代码:
class TimeUpdated implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; // 新增div标识字段 public $divId; public $timechanged; public function __construct($divId, $timechanged) { $this->divId = $divId; $this->timechanged = $timechanged; } public function broadcastOn() { return new Channel('time-updated'); } // 可选:自定义广播事件名,简化前端绑定代码 public function broadcastAs() { return 'time.updated'; } }
2. 修改控制器逻辑
在返回时间前触发广播事件,传入对应div的id和时间值:
public function gettime($id = null) { $result = time(); // 触发广播事件 TimeUpdated::dispatch($id, $result); return $result; }
3. 修正前端JS代码
修复原有选择器错误、字符串拼接错误,新增Pusher推送后的DOM更新逻辑:
$(document).ready(function(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); // 仅选中ID前缀为divId的div元素,避免误选其他DOM document.querySelectorAll('div[id^="divId"]').forEach(function(node) { // 提取div的数字标识,比如divId1提取出1 const nodeId = node.id.replace('divId', ''); $.ajax({ // JS字符串拼接用+,不是PHP的. url: '/getTime/' + nodeId, method: 'get', success: function(data) { // 初始加载直接赋值 $(node).text(data); } }); }); // Pusher 配置 var pusher = new Pusher('xxxxxxxxxxxxxxx', { cluster: 'eu', encrypted: true }) var channel = pusher.subscribe('time-updated'); // 如果使用了自定义事件名就绑定time.updated,未使用则替换为原全类名App\Events\TimeUpdated channel.bind('time.updated', function(data){ // 匹配对应ID的div更新时间 $(`#divId${data.divId}`).text(data.timechanged); }); });
4. 可选:定时全局推送时间
如果需要不依赖用户请求、自动定时更新所有div时间,可以在Laravel调度任务中添加配置,编辑app/Console/Kernel.php的schedule方法:
$schedule->call(function () { // 遍历3个div的ID for ($i = 1; $i <=3; $i++) { TimeUpdated::dispatch($i, time()); } })->everyMinute(); // 可根据需求调整间隔,比如everyThirtySeconds()
配置完成后开启Laravel队列工作进程和调度任务监控即可生效。
内容的提问来源于stack exchange,提问作者KovidaK
相关产品推荐
相关产品推荐

