在我的命名空间中使用 socket.io
我将 socket.io 作为代码的一部分提供给第三方网站使用。我不希望它污染全局命名空间(例如,不同版本的 io 会发生冲突),而是让它仅作为我的库的一部分工作,因此它将被命名空间并仅从
MyLibrary.io
我该怎么办?
I'm shipping socket.io as part of my code for 3rd party sites to use. I don't want it to pollute the global namespace (e.g. different versions of io will collide) but rather make it work only as part of my library, So it will be namespaced and called only from
MyLibrary.io
How do I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您可以完全控制该文件,因此最简单的方法就是修改该文件以在新位置加载 socket.io。
我想说的最简单的方法是将
dist/socket.io.js
的内容包装起来,这将使文件将
io
加载到MyLibrary 上
相反。 SocketIO 与许多库一样,使用this
来决定如何加载内容。在浏览器环境中,this
是对象window
,但是通过将函数包装在所有内容上,您可以控制this
并将其更改为您自己的使用call
方法来获取值。许多其他库(尽管不是 socketIO)都有一个帮助器来避免这个问题。他们通常有一个名为
noConflict()
的方法。例如,如果您想避免 jQuery 出现这样的问题,您可以这样做:这是可行的,因为当 jQuery 加载时,它会保存对先前加载版本的引用,以便在需要时可以将全局对象设置回来他们是怎样的。
Since you have total control over the file, then the easiest thing to do would be to just modify the file to load socket.io at a new location.
The easiest way I would say to do that would be to wrap the contents of
dist/socket.io.js
withThat will make the file load
io
ontoMyLibrary
instead. SocketIO, like many libraries, usesthis
to decide how to load things. In a browser circumstance,this
is the objectwindow
, but by wrapping a function around everything, you can controlthis
and change it to your own value by using the methodcall
.Many other libraries, though not socketIO, have a helper to avoid exactly this problem. Often they have a method called
noConflict()
. For example, if you wanted to avoid a problem like this for jQuery, you could do:That works because when jQuery loads, it saves a reference to the previously loaded version, so that if it needs to, it can set the global objects back to how they were.
似乎建议的方法(Issue #85)是按照正常方式加载它,然后运行这两行:
socket.io.js
中的代码 only 将io
变量添加到>窗口
。您可以修改
socket.io.js
中的代码,但这可能会使将来的维护变得困难,因为您必须跟踪对该文件所做的更改并将其传播到较新版本的socket.io.js
。起初,我认为你可以用
module.exports
做一些事情,因为它有 CommonJS 格式,但是,在阅读代码后,我意识到这只是构建socket.io.js
文件之前组织事物的方式。请参阅此处的文件目录了解我所指的内容。It seems that the suggested way to do this (Issue #85) is to load it as per normal then run these two lines:
The code in
socket.io.js
only adds theio
variable to thewindow
.You could modify the code in
socket.io.js
but that might make it hard to maintain in the future since you would have to track changes you make to that file and propagate them into newer versions ofsocket.io.js
.At first, I thought you could do something with
module.exports
since it had the CommonJS format, however, after reading the code, I realized it's just the way things were organized before building thesocket.io.js
file. See the file directory here for what I'm referring to.