Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created June 18, 2014 21:10
Show Gist options
  • Save mhulse/aac5d6782868b612320b to your computer and use it in GitHub Desktop.
Save mhulse/aac5d6782868b612320b to your computer and use it in GitHub Desktop.
Just an example JS plugin pattern I like to use as starting point for utility-esque JS projects/needs.
/**
* Plugin example using pure javascript.
*
* Patterns used: "closure", "alias" and "namespace extension".
*
* @see http://stackoverflow.com/a/12774919/922323
* @param {object} stub
* @param {object} window
* @param {object} document
* @param {undefined} undefined
* @return void
*/
(function(stub, window, document, undefined) {
'use strict';
stub.init = function(argument) {
// Call public function:
this.public_func(argument);
// Call private function:
_private_func_1(argument);
// Call private function with a given `this` value:
_private_func_2.call(this, argument);
var $wallpaper = document.getElementById(argument);
console.log($wallpaper);
var json = $wallpaper.getAttribute("data-wallpaper-options");
var obj = window.JSON.parse(json);
console.log(obj.image1);
};
stub.public_func = function(argument) {
console.log('public_func', this, argument);
};
var _private_func_1 = function(argument) {
console.log('_private_func_1', this, argument);
},
_private_func_2 = function(argument) {
console.log('_private_func_2', this, argument);
};
}((window.STUB = window.STUB || {}), window, document, undefined));
STUB.init('wallpaper');
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<a id="wallpaper" href="http://google.com" data-wallpaper-options='{"image1":"1230x800.jpg","image2":"1560x800.jpg"}'></a>
<script src="plug-stub.js"></script>
<script>
/*
window.onload = function() {
var console = (window.console || { log : function() {}, warn : function() {} });
console.log('foo', 'yo');
STUB.init('foo');
STUB.public_func('baz');
};
*/
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment