Integrating Public Methods and Callbacks
Add public methods to your plugins for external interaction and incorporate callback functions to allow users to hook into specific plugin events.
Interact with Your Plugins
Great plugins aren't just standalone. They let users interact with them after initialization! This lesson teaches you how to add public methods for external control and callback functions for custom reactions.
- Public Methods: Functions users can call on an initialized plugin instance.
- Callbacks: Functions that run when specific events happen inside your plugin.
Plugin Basics Revisited
Recall that jQuery plugins are often wrapped in an Immediately Invoked Function Expression (IIFE) to prevent global scope pollution. This structure provides a secure place for your plugin's logic and internal variables.
We'll build upon this familiar pattern.
(function($) {
$.fn.myPlugin = function(options) {
// Default settings
var settings = $.extend({}, $.fn.myPlugin.defaults, options);
return this.each(function() {
var $this = $(this); // The element the plugin is applied to
// Plugin logic goes here
console.log("Plugin initialized on: " + $this.attr('id'));
});
};
// Default options
$.fn.myPlugin.defaults = {
message: "Hello from plugin!"
};
})(jQuery);
// How to use (in HTML <div id="myElement"></div>):
// $('#myElement').myPlugin();All lessons in this course
- Plugin Design Patterns and Scoping
- Building Configurable and Reusable Plugins
- Integrating Public Methods and Callbacks