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:
Here’s video 1 in case you missed it:
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:
Modular JS #2 – Object Literal Pattern pt 2:
Modular JS #3 – Revealing Module Pattern:
Original source
49 responses to “Modular Javascript #3 – Revealing Module Pattern Javascript Tutorial”
Your explanation to IIFE was so simple.
What a good explanation of IIFE. I never thought about it in that way, "Evaluating expression". Keep up with these awesome videos
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?
what render function does?
1:07, oh I donno wats that all abt…:D
2:07 we can also make it work by this way:
1..toString() // notice double point
1 .toString() // notice space between `1` and `.toString`
this is gold
hey you can do 1..toString()
it's not about types. just you need to add one more dot cause the first one is for decimal place.
This helped me a lot! 🙂
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…
})()
never occurred to me that IEFE can be use so creatively to create truly private fields!
on code pen you havent set condition if name !== empty
separate event handlers from actions Sir, you won't to deal with that event typeof funkiness
Naming convention question: should the module name's first character capitalized?
Man, I seriously need your help in explaining me closures..
Btw great content (y)
When you refered to a "self executing anonymous function" I think you should refer to it as a immediately invoked function expression or IIFE , the key to understanding it is to understand the difference between a function statement and a expression, what the () do is convert the function statement into a function expression.
wow, https://youtu.be/pOfwp6VlnlM?list=PLoYCgNOIyGABs-wDaaxChu82q_xQgUb4f&t=67 – this looks fun – i came here from the flux tutorial to pubSub!
OMG.. Where were this videos!!.. Why YouTube haven't recommended this to me.. Thanks a lot.. You're damn good
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!
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
people = shit
I just love you man. Your method of conveying principals is amazing
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 )
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?
you should not query dom in the function body put them in function, call that function in init, right now it is executed when the script is read by the browser and you query the dom even if you are not using this particular module on a given page, leads to performance issues same goes with event handlers.
Great content. Had an a-ha moment when you explained javascript evaluations at the start of the video.
sooooooo good
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?
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.
Clarifying tutorials, thanx 👍
This pattern causes mysterious errors. Errors that I can not explain. For example says not defined for a global variable.
Great explanation! Also have been doing js for a while without understanding what " (function(){ …})() " is actually doing.
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.
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… })
});
truth be revealed…god shows up indeed…when you delete Laura 🙂
Hi I just want to say, if it wasnt for you, maaaan I dont even know….I'm really grateful, I look at your code and i feel like jumping in. You helped me get through 2 and a half years of college.
or…
$button.on('click', function(e) { addPerson($input.val()); });
function addPerson(value) {
// push value to people
}
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?
Amazing series! Love it <3
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?
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!
if you like this you will love my channel, it gives practical examples.
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()
With ES2015, there probably won't be a need to do revealing module or object literal patterns right?
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.
thats ✔ some good👌👌shit right👌👌th 👌 ere👌👌👌
Quick question. At 8:12 in line 22 how do the "?" and ":" symbols wok? Where can I read more about it?
How do I set whatever DOM I like to var $el from the outside of the object? There would be a case I just want to change #peopleModule to other. Create another function to change the target?
Really cool way to do it.
Thank you.