JSFiddle - React, Tailwind, and code Playground
by peterdrinnan
HTML
<strong>module sub-function</strong>
<br />
Yourlib.setColor('blue');
<br />
<div id="colorbox1" class="colorbox"></div>
<strong>chained function calls</strong>
<br />
Yourlib.getById('colorbox2').setColor('purple');
<br />
<div id="colorbox2" class="colorbox"></div>
<strong>functions called without chaining</strong>
<br />
Yourlib.getById('colorbox3')
<br />
Yourlib.setColor('green');
<br />
<div id="colorbox3" class="colorbox"></div>
<strong>new function added to extended module</strong>
<br />
Yourlib.setAnotherColor('orange');
<br />
<div id="colorbox4" class="colorbox"></div>
CSS
.colorbox{
height: 40px;
width: 40px;
background: #000;
border: #000 1px solid;
margin-bottom: 5px;
}
JavaScript
var Yourlib = (function() {
// privt. var
var selectedEl = {}
// some privt. funct
function something() {
}
return {
setColor : function(newcolor) {
var obj = document.getElementById('colorbox1');
obj.style.background = newcolor;
}
}
}());
// call the original module sub-function
Yourlib.setColor('blue');
/**
* Extend the module again to allow chaining.
* Chainable functions return "this"
*/
var Yourlib = (function (object) {
// private variable to store id of a box
var box = '';
object.getById = function (id) {
box = document.getElementById(id);
return this;
};
object.setColor = function (newcolor) {
box.style.background = newcolor;
return this;
};
object.setAnotherColor = function (newcolor) {
var box = document.getElementById('colorbox4');
box.style.background = newcolor;
};
return object; // return the extended object
}(Yourlib)); // original module passed in as an object to be extended
// example of a chained function call
Yourlib.getById('colorbox2').setColor('purple');
// same functions without chained call
Yourlib.getById('colorbox3')
Yourlib.setColor('green');
// new function within extended module
Yourlib.setAnotherColor('orange');