Skip to content

Instantly share code, notes, and snippets.

@remluben
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remluben/14daad3ebf2d02450e13 to your computer and use it in GitHub Desktop.
Save remluben/14daad3ebf2d02450e13 to your computer and use it in GitHub Desktop.
JavaScript OOP widget pattern factory example
// How to use
// jQuery required ( @see http://jquery.com )
jQuery(document).ready(function ($) {
// we initialize the widget as soon as the document has been loaded
var widget = new app.Widgets.Example(jQuery('#example'));
// if the following HTML DOM element is clicked, we want to open / display our widget
$('.some-trigger').on('click', function () {
widget.open();
});
});
/**
* An object constructor ( actually factory ) draft
**/
// application namespace setup
var app = app || {};
app.Widgets = app.Widgets || {};
// Example widget object
/**
* @param {Object} jQuery element object of the widget outer container HTML DOM element
* @param {Object} additional settings for the widget
**/
app.Widgets.Example = function ($el, options) {
var that = {}, // public symbols, all variables an methods added are accessible using (app.modules.myModule.<functionName>)
priv = {}; // private symbols, not accessible from outside the module function
that.$el = $el;
priv.options = options;
// methods
that.close = function() {
that.$el.show();
};
that.open = function() {
that.$el.hide();
};
// init
// do some initialization stuff here
that.$el.addClass('example-widget');
return that;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment