Skip to content

Instantly share code, notes, and snippets.

@alex-wdmg
Created October 31, 2020 11:49
Show Gist options
  • Save alex-wdmg/93972d586ce3bcf6048a45d691aaf8be to your computer and use it in GitHub Desktop.
Save alex-wdmg/93972d586ce3bcf6048a45d691aaf8be to your computer and use it in GitHub Desktop.
JS Plugin Boilerplate
// Create an immediately invoked functional expression to wrap our code
(function() {
// Define our constructor
this.myPlugin = function() {
// Create global element references
this.element = null;
// Define option defaults
let defaults = {
selector: 'body',
element: null,
className: 'my-plugin',
htmlContent: '<h1>Hello World!</h1>',
};
// Create options by extending defaults with the passed in arugments
if (arguments[0] && typeof arguments[0] === "object") {
this.options = extendDefaults(defaults, arguments[0]);
}
pluginInit.call(this);
};
/**
* Public Methods
*/
myPlugin.prototype.test = function() {
console.log('Test Ok!');
};
myPlugin.prototype.destroy = function() {
pluginDestroy.call(this);
};
/**
* Private Methods
*/
function pluginInit() {
let innerContent;
// Get base element
if (typeof this.options.element == "undefined" || this.options.element == null)
this.element = document.querySelector(this.options.selector);
else
this.element = this.options.element;
console.log(this.element);
// Create element
innerContent = document.createElement("div");
innerContent.innerHTML = this.options.htmlContent;
// Append innerContent to body
this.element.appendChild(innerContent);
// Add base plugin className
this.element.className = this.options.className;
}
function pluginDestroy() {
let innerContent;
innerContent = document.getElementsByName("div");
this.element.removeChild(innerContent);
this.element.className.replace(this.options.className, "");
}
function extendDefaults(options, properties) {
let property;
for (property in properties) {
if (properties.hasOwnProperty(property)) {
options[property] = properties[property];
}
}
return options;
}
}());
var plugin = new myPlugin({
element: element,
className: 'my-plugin',
htmlContent: '<h1>Hello World!</h1>',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment