jquery自定义事件命名约定
那么,它们是什么?
我的意思是,我知道存在命名空间 - 但如果我的事件名称太明显,比如说 submit
,那么仅添加命名空间 submit.myns
并不能阻止触发它当触发标准submit
时。
好的,我知道, submit
是一个很糟糕的例子,但是如果我想使用与我正在使用的某些插件相同的名称?当我有一个大网站,有很多自定义事件和很多插件时,这可能是一个问题,特别是如果我想保持事件名称简单且有意义。
那么您是否使用某种约定,例如前缀/后缀(例如 myns:event
/myns_event
)?还是我太担心了,我的担心是多余的?
编辑:
如果您必须对有界事件进行分组以便于轻松解除绑定,那么命名空间非常有用。但其工作方式无法确保处理程序 click.my
仅由 click.my
触发。为此,我们必须将其命名为不同的名称,例如 my_click
- 然后我们保留有意义的名称,我们有信息表明这是我们的事件(并且有人使用它的可能性较小),并且我们仍然可以受益于标准事件命名空间。
一些代码来查看差异:http://jsfiddle.net/h2kuN/1/
So, what are they?
I mean, I know there is namespacing - but if My event name is too obvious, let say submit
, then just adding a namespace submit.myns
doesn't prevents triggering it when standard submit
is triggered.
Ok, I know, submit
is quite bad example, but if I want to use same name as some plugin I'm using? When I have big site, with lots of custom events and lots of plugins, this might be a problem, especially if I want to keep event names simple and meaningful.
So do you use some kind of conventions, like prefixes/postfixes (like myns:event
/myns_event
)? Or maybe I'm too concerned and my worries are unfounded?
EDIT :
Namespaces are great, if you have to group bounded events for easy unbinding. But the way its working, is no way to be sure that handler click.my
is triggered only by click.my
. For this, we have to name it different, like my_click
- then we keep meaningfull name, we have info that it is our event (and it is less probably that someone uses it), and we still can benefit from standard events namespacing.
Some code to see the differences: http://jsfiddle.net/h2kuN/1/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
命名空间可以解决这个问题 - 但只有每个人都使用它。
您可以绑定并触发季节性插件的
christmas.adam
,我也可以绑定并触发christmas.bennett
,我们不会干涉。但如果有人出现并触发圣诞节
,那么我们的两个插件都会被触发。发生这种情况是因为如果您将处理程序绑定到
event.namespace
,那么触发event
将触发您的处理程序。这在 jQuery API 文档中并不清楚,但从 jQuery 1.7.1 开始是这样的。因此(除了可以轻松地一次解除绑定多个处理程序之外),命名空间还可以保护其他代码,而不是您的代码。
Namespacing solves this problem — but only if everybody uses it.
You can bind to and trigger
christmas.adam
for your seasonal plugin, and I can bind and triggerchristmas.bennett
and we won't interfere. But if somebody comes along and triggerschristmas
then both our plugins will be triggered.This happens because if you bind a handler to
event.namespace
, then triggeringevent
will trigger your handler. This isn't clear in the jQuery API documentation, but it is true as of jQuery 1.7.1.So (apart from making it easy to unbind many handlers at once), namespacing serves to protect other code, not yours.