使用 JavaScript 取消订阅已发布的事件
我有一个网站,用户可以动态添加小部件。这些小部件使用 Peter Higgins pub/sub 插件来 $.(subscribe)
到我从另一个“核心”模块 $.(publish)
的事件。
我在自己的名称空间中有小部件,如下所示:
km.widget.name1,
km.widget.name2,
等等。
因此 $.(subscribe)
创建的句柄不是全局的。
当用户决定从自定义页面删除小部件时,我不知道如何取消订阅这些小部件。
另外,我怎么知道要取消订阅哪个小部件?
I have a website that users can dynamically add widgets to. These widgets use the Peter Higgins pub/sub plug-in to $.(subscribe)
to an event that I $.(publish)
from another 'core' module.
I have widgets in their own name space like this:
km.widget.name1,
km.widget.name2,
etc.
So the handles created by $.(subscribe)
aren't global.
I do not know how to unsubscribe these widgets when the user decides to remove the widget from their custom page.
Also, how would I know which widget to unsubscribe from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这并不能直接解决您的问题,但很可能对您有所帮助。 这是 Sam Clearman 最近的博客。他描述了一种在不使用该插件的情况下处理发布/订阅事件的方法:
这样做,您也许能够解决当前的问题。
This doesn't solve your problem directly, but it may very well help you out. This is a recent blog by Sam Clearman. He describes a way to handle publish/subscribe events without using that plugin:
Doing it this way, you may be able to solve your current issues.
我之前没有使用过 pubsub 插件,只是浏览了一下 源代码,看起来你可以像订阅一样取消订阅,只需使用
$.unsubscribe(...)
而不是$.subscribe(. ..)
。这是您已经知道的事情吗?问题是由您的小部件命名空间引起的吗?无论如何,我不太确定你所说的命名空间是什么意思,因为 JavaScript 不支持真正的命名空间(只是对象 - 我猜这就是你正在使用的)。
I haven't used the pubsub plugin before, but I just glanced at the source code and it looks like you can unsubscribe in exactly the same as as you subscribe, just using
$.unsubscribe(...)
rather than$.subscribe(...)
.Is this something you already know, and the problem is caused by your widget namespacing? I'm not really sure of what you mean by namespacing, anyway, since JavaScript doesn't support true namespaces (just objects - which I'm guessing is what you're using).