命名空间 jQuery 插件
假设我们有以下 jQuery 插件(每个插件都在单独的文件中):
$.fn.foo
$.fn.foo.bar
$.fn。 foo.baz
我使用标准 jQuery 插件模式。第一个实际上是其名称空间的其余插件的代理或“外观”。 例如,当我调用 $('#el').foo()
时,在幕后我也会调用:
var context = this; // context is equal to $('#el') $(context).foo['bar'].apply(context); $(context).foo['baz'].apply(context);
当我只想调用only时,有两个问题(不带 $.fn.foo
) $('#el').foo.bar()
。第一个问题是没有 $.fn.foo
命名空间,但我可以创建它,所以这实际上没有问题。第二个问题是 $.fn.foo.bar
中的 this
等于 document
对象,但我想等于 $('#el')
.我怎样才能做到这一点?
因此,长话短说,两者都应该有效:
$('#el').foo(); // This also calls foo.bar and foo.baz under the hood $('#el').foo.bar(); // I'm calling foo.bar explicitly
Let's assume that we have following jQuery plugins (each of them in separate files):
$.fn.foo
$.fn.foo.bar
$.fn.foo.baz
I use standard jQuery plugin pattern. The first one is actually a proxy or "facade" to the rest plugins of it's namespace.
For example, when I call $('#el').foo()
, under the hood I also call:
var context = this; // context is equal to $('#el') $(context).foo['bar'].apply(context); $(context).foo['baz'].apply(context);
There are two problem when I want to call only (without $.fn.foo
) $('#el').foo.bar()
. The first problem is that there are no $.fn.foo
namespace but I can create it, so this is actually no problem. The second problem is that this
inside $.fn.foo.bar
is equal to document
object but I want to be equal to $('#el')
. How can I do that?
So, making a long story short, both should work:
$('#el').foo(); // This also calls foo.bar and foo.baz under the hood $('#el').foo.bar(); // I'm calling foo.bar explicitly
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您可能只需要遵循不同的插件模式。这是一个很好的 jQuery 插件模式存储库,但您可能想看看将是 命名空间模式 - 如果名称空间尚不存在,您将看到名称空间最初是如何定义的,这使您可以更轻松地从单个名称空间跨多个脚本进行扩展。
更新:嗯,我还在学习,所以我不会说我是这方面的专家,但试图得到这个
$('#el').aaa.bbb.ccc()
工作对我来说真的很混乱。也许最好不要使用这种格式,而是这样做(demo):因为这样就可以了设置起来相对容易:
I think you might just need to follow a different plugin pattern. Here is a nice repository of jQuery plugin patterns, but the one you might want to look at would be the namespace pattern - you'll see how the namespace gets defined initially if it doesn't already exist, and this allows you to more easily extend from a single namespace across multiple scripts.
Update: Hmm, I'm still learning so I wouldn't say I'm an expert at this, but trying to get this
$('#el').aaa.bbb.ccc()
to work got really messy for me. Maybe it would be better to not use that format, but instead do this (demo):because then it is relatively easy to set up: