Revealing Module Pattern

An easy way to encapsulate otherwise convoluted code. Also by not just exposing a public init() function, you can run tests on other public functions. Only downside is you can't run tests on private functions from the public pointers.

by petran

HTML

<div>
    <img src="http://placekitten.com/500/200" width="500" height="200" />
</div>
<p id="cat-name">Set the name, then get it.</p>
<input id="set" type="button" value="catModule.setCatName('Miffles')" />
<input id="get" type="button" value="catModule.getCatName()" />

CSS

@import url(http://fonts.googleapis.com/css?family=Francois+One);
body {
    width:510px;
    margin:0 auto;
    margin-top:20px;
    text-align:center;
}
img {
    border:5px solid #561B00;
    -webkit-filter:sepia(50%);
    -webkit-box-shadow:0 19px 11px -15px #000;
}
p {
    font-size:2em;
    font-family:'Francois One', sans-serif;
    padding:10px;
}

JavaScript

var catModule = function() {

    // Private variable
    var secretCat = "Random text only accesible through this module";

    function secretCatFunction() {
        $('#cat-name').text(secretCat);
    }

    function publicSetCatName(catName) {
        secretCat = catName;
    }

    function publicGetCatName() {
        secretCatFunction();
    }

    // Return an object containing pointers to private functions
    return {
        setCatName: publicSetCatName,
        getCatName: publicGetCatName
    };

}();

$('input').click(function() {
    switch (this.id) {
    case "set":
        catModule.setCatName("Miffles");
        break;
    case "get":
        catModule.getCatName();
        break;
    }
});