【问题标题】:Use class defined in file in script tag Laravel view [closed]在脚本标签 Laravel 视图中使用文件中定义的类 [关闭]
【发布时间】:2018-01-13 16:43:43
【问题描述】:

我尝试在 laravel 中开发一个项目,除此之外,我必须使用 socket.io。 我在自己的文件中实现了一个类作为 socket.io-client 的包装器。 我在 laravel 视图中导入该文件。

我想在 laravel 视图的脚本标签中实例化一个套接字对象,以便能够从该视图传递一个变量,但我得到这个错误:Uncaught ReferenceError: Socket is not defined

问题是,我可以在脚本标签中使用导入文件中定义的类吗?

LE:提供代码

Laravel 视图

@section('scripts')
    <script src="{{ asset('js/diagram.js') }}"></script>
    <script src="{{ asset('js/socket.js') }}"></script>
    <script>
        let socket = new Socket("http://localhost:8080", {!! $id !!});
        socket.connect();
    </script>
@endsection

套接字包装器(只是其中的一部分)

import io from 'socket.io-client';

class Socket 
{
    constructor(strURL, diagramId) 
    {
        this.strURL = strURL;
        this.diagramId = diagramId;
    }

    connect()
    {
        this.socket = io.connect(this.strURL);
        // Send the diagram id to include socket into a room
        this.socket.emit('diagram', this.diagramId)
    }
}

【问题讨论】:

  • 代码在哪里?
  • 我添加了代码。我希望现在没事:)

标签: javascript node.js laravel socket.io


【解决方案1】:

js 尝试执行内联脚本时,socket.js 似乎还没有加载

【讨论】:

  • Socket 类应该已经加载了,不是吗?脚本不是按顺序加载的吗?
  • 是的,但它们是异步加载的。所以你可以用 document.addEventListener('onload', function (){})$(function () {}) 包装你的代码用于 jquery 案例
  • 成功了。谢谢
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 2020-09-04
  • 1970-01-01
相关资源
最近更新 更多