eventsjquery-pluginsplugin-architecture

Create a plugin, expose events


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.


Solution

  • 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 even click.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.