Modular Javascript #3 – Revealing Module Pattern Javascript Tutorial

The revealing module pattern allows us to create private variables in a Javascript Module.
Here’s a writeup on this pattern:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
Here’s the code for this video:
http://codepen.io/anon/pen/ZGoKYN?editors=101
Here’s video 1 in case you missed it:
https://www.youtube.com/watch?v=HkFlM73G-hk&index=18&list=PLoYCgNOIyGACnrXwo5HMCfOH9VT05znGv

We write a revealing module pattern by starting with a self-executing anonymous function also known as an IIFE (immediately invoked function expression).

This runs a function and sets it’s return value as our module’s value. If we return an object of methods, then those methods are what other modules have “public” access to. What’s nice about this, is we can create any variables within the function and no other modules have access to them unless we expose them via our return object.

Modular JS #1 – Object Literal Pattern pt 1:
https://www.youtube.com/watch?v=HkFlM73G-hk&index=1&list=PLoYCgNOIyGABs-wDaaxChu82q_xQgUb4f

Modular JS #2 – Object Literal Pattern pt 2:
https://www.youtube.com/watch?v=m-NYyst_tiY&index=2&list=PLoYCgNOIyGABs-wDaaxChu82q_xQgUb4f

Modular JS #3 – Revealing Module Pattern:
https://www.youtube.com/watch?v=pOfwp6VlnlM&index=3&list=PLoYCgNOIyGABs-wDaaxChu82q_xQgUb4f

Comments

Joshua Ryder says:

Awesome video. Been working with javascript a lot (only smaller scripts). But lately my projects are growing a lot. Knew about this pattern, just never really sat down learning it. Nice quick introduction.

bohussaain says:

Hi Will, I just got confused between this video and the previous one. Why did you remove all the function you wrote in the previous video and replaced them with comments or different looking methods. ex. init, casheDOM, binding?
Is there a use case where this way is more suitable and the other is not?

Michael Mammoliti says:

So the revealing module pattern (in this case) is useful if you don’t need to instantiate an huge amount of objects? The object literal is focused on performances.. Am I wrong?

Rajagopal CR says:

OMG.. Where were this videos!!.. Why YouTube haven’t recommended this to me.. Thanks a lot.. You’re damn good

Prabhas Joshi says:

wow, https://youtu.be/pOfwp6VlnlM?list=PLoYCgNOIyGABs-wDaaxChu82q_xQgUb4f&t=67 – this looks fun – i came here from the flux tutorial to pubSub!

rajeshwar chinna says:

1:07, oh I donno wats that all abt…:D

无可救药 says:

use return to make the api out

Jessy Cormier says:

Just wanted to thank you for putting these videos together. I had been “taught” how to program with the “crap” you described in your first video and it was always annoying and hard to deal with. Going over these patterns is very refreshing so thank you for taking the time to put together the examples and resources.

Alique Williams says:

With ES2015, there probably won’t be a need to do revealing module or object literal patterns right?

Oktaviardi Pratama says:

on code pen you havent set condition if name !== empty

AmxCsifier says:

separate event handlers from actions Sir, you won’t to deal with that event typeof funkiness

Caleb Prenger says:

Your delete person function makes no sense. first off, you rerender the entire module instead of just removing the “$remove”. Also, i = event does not return a number. if the event is not a number, it returns a -1. I’m not sure what your function is doing

-.- Cat says:

never occurred to me that IEFE can be use so creatively to create truly private fields!

Konstantinos Papakonstantinou says:

Great content. Had an a-ha moment when you explained javascript evaluations at the start of the video.

Tom Riecken says:

For me, MustacheJS won’t run unless I include it inside a document ready function, and I can’t define an API when I put it inside document ready.

EDIT- got around this by scoping properly – globals

var people;
$(document).ready(function(){
people = (function(){ ..api stuff… })
});

Tincho says:

I have a question, why the line 13 works after calling addPerson? addPerson adds an item to the array and calls render, which rewrites the ul inner html, but the binding is happening when the self executing function executes, and that happen once, right?

Ashwinkumar Sharma says:

Your explanation to IIFE was so simple.

Juned says:

What a good explanation of IIFE. I never thought about it in that way, “Evaluating expression”. Keep up with these awesome videos

elieghossein says:

I just love you man. Your method of conveying principals is amazing

Tim Garlick says:

I am still waiting for my a-moment. Would there be any difference between

var people = function() {
//actions…
}
people();

and what your wrote in your video

var people = (function() {
//actions…
})()

Judge Lead says:

people = shit

Leira Hua says:

Great Video~ I’m new to JavaScript, this video helped a lot, thanks.

But about why the immediately-invoked function expression (IIFE) need to be wrapped in parentheses and why 1.toString() doesn’t work around 2:10 https://youtu.be/pOfwp6VlnlM?t=2m10s, I think it might be because of different reason.

I think the reason the IIFE need to be wrapped in parentheses is to make it a function expression, rather than a function statement.

function () {alert();}() // 1 Uncaught SyntaxError: Unexpected token (

Line 1 doesn’t work not because the function is not evaluated before called, it’s not a semantic error, it’s a SyntaxError.

A line starting with “function” is function statement. In line 1, the function was defined as a function statement, the statement ends with ‘}’, JavaScript doesn’t expect any characters after that. So it is a SyntaxError with Unexpected token ‘(‘.

(function () { alert(); }) () // 2 works

While line 2 works, as it it starts with ‘(‘ not ‘function’, so it’s not a function statement, it’s a function expression. As an expression, it can be used in another expression, so it is just invoked by the subsequent ‘()’, there is no SyntaxError.

(function () { alert(); } ()) // 3 works too

For the same reason, line 3 works too, the function isn’t defined in parentheses, but still can be invoked right away, as it is a function expression.

var a = function () { alert(); } () // 4 works too

Line 4 also works, assignment also force it to function expression.

1.toString() // 5 Uncaught SyntaxError: Invalid or unexpected token

Reason why 1.toString() doesn’t work is also a SyntaxError, I quote from http://stackoverflow.com/questions/12701609/1-tostring-syntaxerror-in-javascript:

”’
The parser is trying to treat 1. as the start of a floating-point literal — only toString turns it into an invalid number.

Compare with:

1.0.toString()
”’

Sorry, too long.

cav3man82 says:

Great explanation! Also have been doing js for a while without understanding what ” (function(){ …})() ” is actually doing.

Lalinda Dias says:

Great Tutorials, btw I have an issue. Do I need to install any libraries to use ‘mustache.render’. I checked this on every browser and ‘mustache.render’ does not recognize by browsers. Can you help me?

Mohammad Al-Abbasi says:

Also can you explain why you put event as a parameter in your deletePerson method?

Oussama Amassuo says:

hey Will ! you are awesome ! so are your lessons
for this one, i still have to catch up on (splice.delegate) felt a bit sad not fully understandin you in this video,

but to make the day worth it , i did Add a Keypress event on input, made it work !!! (thanks to your other vide ofc )
this kinda compensate not understandin this at 100%.. but soon ; i WILL

you are a great mentor !!

p.s: (bad english is good english )

Deepak Singh says:

truth be revealed…god shows up indeed…when you delete Laura :)

tommy says:

sooooooo good

Advanced Web Academy says:

if you like this you will love my channel, it gives practical examples.

jbob34345 says:

Naming convention question: should the module name’s first character capitalized?

GifCo says:

Hey Will, just watching these over again!! lol Question, are there any benefits to using Object Literal modules instead of a revealing module? Is this the new accepted pattern that we should use and the object literal is the old way things used to be done? Or do they both still have their place?

无可救药 says:

some out some in

shapan sutradhar says:

what render function does?

m.ali petek says:

This pattern causes mysterious errors. Errors that I can not explain. For example says not defined for a global variable.

Jakub Spręga says:

Amazing series! Love it <3

Matěj Mazur says:

This helped me a lot! :)

J IJzerman says:

I stopped watching. The code is quite sloppy and your explanation of 1.toString() is just wrong. The reason it fails is not because it’s a number, the reason it fails is that “1.” is ambiguous to the engine: the dot can indicate a float or a property accessor. It will work fine if you type 1..toString()

Dmitry says:

2:07 we can also make it work by this way:
*1..toString()* // notice double point
*1 .toString()* // notice space between `1` and `.toString`

Mark Christoper Vizcarra says:

or…

$button.on(‘click’, function(e) { addPerson($input.val()); });

function addPerson(value) {
// push value to people
}

Ankit Suvarna says:

Man, I seriously need your help in explaining me closures..
Btw great content (y)

MsFCliverpool says:

With ES6, are these patterns going to be obsolete? Also, is there ever a reason to use the object literal pattern over this revealing module pattern? Thanks for the videos!

Carpio Erwin John T. says:

Hi…you have amazing videos…. thanks! just wanted to ask a newbie question…. I tried using your “REVEAL PATTERN” and used some DOM CACHING…. then ran it through webpack (again using one of your excellent videos)… but for some reason I can’t CACHE the DOM anymore…..if I manually use a jquery search within the new scripts.min.js produced by webpack…. it works but the dom cache $el is an empty value….thanks again!

Write a comment

*

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.


Do you like our videos?
Do you want to see more like that?

Please click below to support us on Facebook!

Send this to a friend

▷ Other ReviewsVehicles   Show Cars   Motorbikes   Scooters   Bicycles   Rims & Tires   Luxury BoatsFashion   Sunglasses   Luxury Watches   Luxury Purses   Jeans Wear   High Heels   Kinis Swimwear   Perfumes   Jewellery   Cosmetics   Shaving Helpers   Fashion Hats   Modeling TipsFooding   Chef Club   Fooding Helpers   Coktails & LiquorsSports   Sport Shoes   Fitness & Detox   Golf Gear   Racquets   Hiking & Trek Gear   Diving Equipment   Ski Gear   Snowboards   Surf Boards   Rollers & SkatesEntertainment   DIY Guides   Zik Instruments   Published Books   Music Albums   Cine Movies   Trading Helpers   Make Money   Fishing Equipment   Paintball Supplies   Trading Card Games   Telescopes   Knives   Vapes   GameplaysHigh Tech   Flat Screens   Tech Devices   Camera Lenses   Audio HiFi   Printers   USB Devices   PC Hardware   Network Gear   Cloud Servers   Software Helpers   Programmer Helpers   Mobile Apps   Hearing AidsHome   Home Furniture   Home Appliances   Tools Workshop   Beddings   Floor Layings   Barbecues   Aquarium Gear   Safe Boxes   Office Supplies   Security Locks   Cleaning ProductsKids   Baby Strollers   Child Car Seats   Remote ControlledTravel   Luggages & Bags   Airlines Seats   Hotel Rooms   Fun Trips   Cruise Ships   Mexico Tours