Last active
May 6, 2016 12:36
-
-
Save ohvitorino/7a299fe6e0c7f4f32480d50a06bf8636 to your computer and use it in GitHub Desktop.
Revealing Module Pattern in Javascript
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 people = (function(){ | |
var people = ['Will', 'Steve']; | |
//cache DOM | |
var $el = $('#peopleModule'); | |
var $button = $el.find('button'); | |
var $input = $el.find('input'); | |
var $ul = $el.find('ul'); | |
var template = $el.find('#people-template').html(); | |
//bind events | |
$button.on('click', addPerson); | |
$ul.delegate('i.del', 'click', deletePerson); | |
_render(); | |
function _render() { | |
$ul.html(Mustache.render(template, {people: people})); | |
} | |
function addPerson(value) { | |
var name = (typeof value === "string") ? value : $input.val(); | |
people.push(name); | |
_render(); | |
$input.val(''); | |
} | |
function deletePerson(event) { | |
var i; | |
if (typeof event === "number") { | |
i = event; | |
} else { | |
var $remove = $(event.target).closest('li'); | |
i = $ul.find('li').index($remove); | |
} | |
people.splice(i, 1); | |
_render(); | |
} | |
return { | |
addPerson: addPerson, | |
deletePerson: deletePerson | |
}; | |
})(); | |
//people.addPerson("Jake"); | |
//people.deletePerson(0); |
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
<div id="peopleModule"><h1>People</h1> | |
<input placeholder="name" type="text"> | |
<button id="addPerson">Add Person</button> | |
<ul id="people"> | |
<script id="people-template" type="text/template"> | |
{{#people}} | |
<li> | |
<span>{{.}}</span> | |
<i class="del">X</i> | |
</li> | |
{{/people}} | |
</script> | |
</ul> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on Modular Javascript #3 - Revealing Module Pattern Javascript Tutorial (Youtube)
https://youtu.be/pOfwp6VlnlM?list=PLoYCgNOIyGABs-wDaaxChu82q_xQgUb4f