• Monday , 11 December 2017

Modular Javascript #3 – Revealing Module Pattern Javascript Tutorial

Code Canyon



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

3d Ocean

Related Posts

49 Comments

  1. Ashwinkumar Sharma
    July 29, 2017 at 06:41

    Your explanation to IIFE was so simple.

  2. Juned
    July 29, 2017 at 06:41

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

  3. bohussaain
    July 29, 2017 at 06:41

    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?

  4. shapan sutradhar
    July 29, 2017 at 06:41

    what render function does?

  5. rajeshwar chinna
    July 29, 2017 at 06:41

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

  6. Dmitry Leo
    July 29, 2017 at 06:41

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

  7. renetchi
    July 29, 2017 at 06:41

    this is gold

  8. victor 오승현
    July 29, 2017 at 06:41

    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.

  9. Matěj Mazur
    July 29, 2017 at 06:41

    This helped me a lot! 🙂

  10. Tim Garlick
    July 29, 2017 at 06:41

    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…
    })()

  11. -.- Cat
    July 29, 2017 at 06:41

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

  12. Oktaviardi Pratama
    July 29, 2017 at 06:41

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

  13. AmxCsifier
    July 29, 2017 at 06:41

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

  14. jbob34345
    July 29, 2017 at 06:41

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

  15. Ankit Suvarna
    July 29, 2017 at 06:41

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

  16. António Santos
    July 29, 2017 at 06:41

    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.

  17. Prabhas Joshi
    July 29, 2017 at 06:41

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

  18. Rajagopal CR
    July 29, 2017 at 06:41

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

  19. Carpio Erwin John T.
    July 29, 2017 at 06:41

    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!

  20. Caleb Prenger
    July 29, 2017 at 06:41

    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

  21. Judge Lead
    July 29, 2017 at 06:41

    people = shit

  22. elieghossein
    July 29, 2017 at 06:41

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

  23. Oussama Amassuo
    July 29, 2017 at 06:41

    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 )

  24. Tincho
    July 29, 2017 at 06:41

    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?

  25. alirz 23
    July 29, 2017 at 06:41

    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.

  26. Konstantinos Papakonstantinou
    July 29, 2017 at 06:41

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

  27. tommy
    July 29, 2017 at 06:41

    sooooooo good

  28. Lalinda Dias
    July 29, 2017 at 06:41

    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?

  29. Leira Hua
    July 29, 2017 at 06:41

    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.

  30. Jesper Sjöling
    July 29, 2017 at 06:41

    Clarifying tutorials, thanx 👍

  31. m.ali petek
    July 29, 2017 at 06:41

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

  32. cav3man82
    July 29, 2017 at 06:41

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

  33. Joshua Ryder
    July 29, 2017 at 06:41

    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.

  34. Tom Riecken
    July 29, 2017 at 06:41

    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… })
    });

  35. Deepak Singh
    July 29, 2017 at 06:41

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

  36. Joshua Williams
    July 29, 2017 at 06:41

    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.

  37. Mark Christoper Vizcarra
    July 29, 2017 at 06:41

    or…

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

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

  38. Michael Mammoliti
    July 29, 2017 at 06:41

    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?

  39. Jakub Spręga
    July 29, 2017 at 06:41

    Amazing series! Love it <3

  40. GifCo
    July 29, 2017 at 06:41

    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?

  41. MsFCliverpool
    July 29, 2017 at 06:41

    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!

  42. Advanced Web Academy
    July 29, 2017 at 06:41

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

  43. J IJzerman
    July 29, 2017 at 06:41

    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()

  44. Alique Williams
    July 29, 2017 at 06:41

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

  45. Jessy Cormier
    July 29, 2017 at 06:41

    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.

  46. gamesbruv
    July 29, 2017 at 06:41

    thats ✔ some good👌👌shit right👌👌th 👌 ere👌👌👌

  47. Gabriel D. Celery
    July 29, 2017 at 06:41

    Quick question. At 8:12 in line 22 how do the "?" and ":" symbols wok? Where can I read more about it?

  48. Norihiro Tsutae
    July 29, 2017 at 06:41

    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?

  49. Burak Tokak
    July 29, 2017 at 06:41

    Really cool way to do it.

    Thank you.

Leave A Comment

You must be logged in to post a comment.