Skip to content

Instantly share code, notes, and snippets.

@evolutionxbox
Created May 10, 2016 11:21
Show Gist options
  • Save evolutionxbox/8ff4bfde8290147abc51070440695d60 to your computer and use it in GitHub Desktop.
Save evolutionxbox/8ff4bfde8290147abc51070440695d60 to your computer and use it in GitHub Desktop.
Object Compositional using Closures
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Object Composition</title>
</head>
<body>
<h1>
<a class="first" href="#">First</a>
<a class="second" href="#">Second</a>
</h1>
<script src="object-composition.js"></script>
</body>
</html>
var Openable = function Openable() {
var isOpen = false;
function open(callback) {
isOpen = true;
callback && callback();
}
function close(callback) {
isOpen = false;
callback && callback();
}
function toggle(callback) {
isOpen ? close(callback) : open(callback);
}
return {
get isOpen() {
return isOpen;
},
open: open,
close: close,
toggle: toggle
};
};
var Thing = function Thing(dom) {
var openable = Openable();
dom.addEventListener('click', function(event) {
event.preventDefault();
openable.toggle(clickCallback)
});
function clickCallback() {
console.log(dom.textContent + openable.isOpen);
}
return {
target: dom,
get isOpen() {
return openable.isOpen;
},
close: openable.close,
open: openable.open,
toggle: openable.toggle
};
};
var first = Thing(document.querySelector('.first'));
var second = Thing(document.querySelector('.second'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment