I 'm currently using this pattern to create and extend a globally accessible custom plugin to be used in a web application:
; // defensive programming: script may be concatenated with others
(function($) {
"use strict";
// allow Plugin to be extended from other scripts
var window.Plugin = window.Plugin || {};
var privateVars = {
// this contains all of the plugin's "private static" fields
};
function someHelperFunction() {
// this is a private method
}
$.extend(window.Plugin,
{
method1: function() {
// this is a public method
},
method2: function() {
// this is a public method
}
});
})(jQuery);
This approach looks fine to me and seems to tick all the boxes. However, since I 'm far from a JS guru I wonder:
Are there any issues with the above pattern that I should be aware of?
Now suppose I want to introduce global configuration that affects the behavior of all subsequent calls to method1
, for example allow the user to register a callback that will get fired every time before method1
executes.
In my mind, this syntax would be nice:
window.Plugin.method1.registerCallback(function() { ... });
window.Plugin.method1(); // take it for a test drive
Is this a good idea? If not, why? What would be a better approach?
To implement this, I would do
window.Plugin = { ... }; // as above
window.Plugin.method1.registerCallback = function() {
// this would write something inside privateVars
};
Is there a more convenient way to add many properties to method1
like this? For example, one that would not require one statement per property to be added. Should I use jQuery.extend for this as well?