创建一个插件,公开事件
如何向我的插件用户公开事件?
我知道我应该使用:
$('#myPluginDiv').trigger('eventName', ["foo", "bar"]);
来触发事件,但我正在寻找描述如何在插件中声明和调用事件的最佳实践。
How do I expose events to my plugin users?
I know that I should use:
$('#myPluginDiv').trigger('eventName', ["foo", "bar"]);
to trigger the event but I'm looking for best practices describing how to declare and invoke events in plugins.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您可以检查一些最常用的插件并做出自己的假设。我们对此没有标准,只有代码约定。
Colorbox(来源:https://github.com/jackmoore/colorbox/blob /master/jquery.colorbox.js) 定义事件名称的前缀和一些常量。它还具有用于触发和运行回调的功能。
jQuery UI(来源:https://github.com/jquery.ui.widget.js" com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js)在小部件类上也有一个用于触发事件的通用函数(用法:https://github.com/jquery/jquery-ui/blob/master/ui/ jquery.ui.dialog.js),但您可以看到事件被硬编码在源的中间,而不是像 Colorbox 上那样将常量编码在顶部。
我个人认为,如果您有很多事件要触发,那么创建常量会更好,并且在我自己的插件中这样做,但如果您只触发 2 或 3 个事件,则没有必要。
辅助函数是必须具备的,并且应该是模板的一部分。
我使用和看到的事件名称都遵循标准CamelCase,例如
beforeClose
。有些人提倡对 Colorbox 的
cbox_open
甚至click.myPlugin
等事件使用前缀(请参阅:http://api.jquery.com/on/#event-names)结论:尝试遵循一般编程的最佳实践和约定,并注意那里有更好的例子。
I think you can inspect some of the most used plugins and make your own assumptions. We have no standards on this, just code convention.
Colorbox (source: https://github.com/jackmoore/colorbox/blob/master/jquery.colorbox.js) defines a prefix and some constants for the event names. It also have a function for triggering and running the callbacks.
jQuery UI (source: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js) also have a common function on the widget class for triggering events (usage: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.dialog.js), but you can see that the events are hard coded on the middle of the source, instead of constants on the top like on Colorbox.
I personally think, and do it in my own plugins, that creating constants is much better if you have a lot of events to trigger, but its not necessary if you will fire only 2 or 3 events.
A helper function is a must have and should be part of your template.
The event names I use and see around all follow the standard CamelCase e.g.
beforeClose
.Some advocate the use of a prefix for events like on Colorbox's
cbox_open
or evenclick.myPlugin
(see: http://api.jquery.com/on/#event-names)Conclusion: try to follow best practices and conventions for programming in general and watch for the better examples out there.
在插件中创建对象文字,例如
in plugin create object litereal like