Created
May 10, 2016 11:21
-
-
Save evolutionxbox/8ff4bfde8290147abc51070440695d60 to your computer and use it in GitHub Desktop.
Object Compositional using Closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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