Skip to content

Instantly share code, notes, and snippets.

@ohvitorino
Last active May 6, 2016 12:36
Show Gist options
  • Save ohvitorino/7a299fe6e0c7f4f32480d50a06bf8636 to your computer and use it in GitHub Desktop.
Save ohvitorino/7a299fe6e0c7f4f32480d50a06bf8636 to your computer and use it in GitHub Desktop.
Revealing Module Pattern in Javascript
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);
<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>
@ohvitorino
Copy link
Author

ohvitorino commented May 6, 2016

Based on Modular Javascript #3 - Revealing Module Pattern Javascript Tutorial (Youtube)
https://youtu.be/pOfwp6VlnlM?list=PLoYCgNOIyGABs-wDaaxChu82q_xQgUb4f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment