JavaScript is interesting in that it enforces no particular structure upon you. “Bring Your Own Organization”, if you will. As I write more and more JavaScript in web app sites, this becomes more and more interesting. How you structure your JavaScript is very important because:
- Done right, it makes code easier to understand for others and yourself re-visting your own code.
- Having a decided-upon structure helps keep future code clean and encourages your declared best practices.
- It makes your code testable.
Before I go any further, let it be known that I am far from a master of JavaScript. There are a lot of smart folks in the JavaScript world that have been doing and talking about this for longer than I knew what a div was.
This has been a topic in my mind lately because I’ve been writing a lot more JavaScript for CodePen, which is very JavaScript heavy. We’ve been using the “Module Pattern” since the beginning and it’s been serving us quite well I think.
Then I posted this article about the making of the Treehouse ad, and within it I also used the Module Pattern for the JavaScript there. Louis Lazaris chimed in that this is how he’s been liking to write JavaScript lately too, and started a bit of a discussion. Louis followed it up with an article explaining his preferred structural pattern.
The Concept
It’s easier to understand concepts like this if there is an example to build from. Let’s say we’re building a news widget. It lists some news articles, and has a button in which you can load more news articles.
The Module
Humble beginnings:
var NewsWidget = {
};
Just an object. I like my JavaScript variables starting with a lowercase character, but Modules get an uppercase first character. Just a convention that helps code readability.
Settings
The news widget will likely have some significant numbers associated with it (e.g. how many articles in it). Also, some significant elements (DOM nodes) that will need to be accessed regularly.
There will be a number of sub-functions of this module that do small specific things. Many of those may need access to these settings and “cached” elements. So, we’ll make the settings available to each of them.
var s,
NewsWidget = {
settings: {
numArticles: 5,
articleList: $("#article-list")
}
};
We’ll get to the sub-function access in a second.
Init Function
To “kick things off” we’ll have just one function be called. This will be consistent across all modules, so you know exactly where to look when you start reading the code and figuring out what happens when.
var s,
NewsWidget = {
settings: {
numArticles: 5,
articleList: $("#article-list"),
moreButton: $("#more-button")
},
init: function() {
// kick things off
s = this.settings;
}
};
The first thing the init
function will do is set the variable s
(which we declared at the same level as the Module) to be a pointer to the settings. Because of where s
was declared, this means all sub-functions of the Module will have access to the settings. Nice.
Binding UI Actions
Alex Vasquez set up a convention for us at CodePen where we would have a function just for binding the UI events. You never write any code that “does stuff” when you bind, you just do the binding and then call another appropriately named sub-function.
var s,
NewsWidget = {
settings: {
numArticles: 5,
articleList: $("#article-list"),
moreButton: $("#more-button")
},
init: function() {
s = this.settings;
this.bindUIActions();
},
bindUIActions: function() {
s.moreButton.on("click", function() {
NewsWidget.getMoreArticles(s.numArticles);
});
},
getMoreArticles: function(numToGet) {
// $.ajax or something
// using numToGet as param
}
};
Combining Files
Chances are the news widget isn’t the only JavaScript you’ll have on a page. There will be lots of Modules you’ll need to load. Perhaps the news widget is on every page of your site, so belongs in a global.js file. This global.js file will ultimately be a a bunch of Modules concatenated, and then a big kick off party.
There are all kinds of ways to handle this concatenation stuff. It could be a dev tool like CodeKit and it’s ability to do appends/prepends. It could be some fancy Grunt.js build script thing.
At CodePen we use Ruby on Rails and it’s asset pipeline. So for us, the global.js file would be something like:
//= require common/library.js
//= require module/news-widget.js
//= require module/some-other-widget.js
(function() {
NewsWidget.init();
SomeOtherModule.init();
})();
That’s All Folks
Pretty darn satisfying way to write JavaScript, I think. It satisfies the three points I made about the importance of structure.
Regarding the testing point, I know that wasn’t discussed much, but I’m sure you can imagine how having smaller specific functions in change of specific tasks are easier to write assertions for. That’s how most JavaScript testing is done (e.g. Jasmine). For instance, in some form of code or another: “I assert that when this function gets this value this other thing happens and is equal to some other value.”
This is the tip of the iceberg. I’ve only just started it, but Learning JavaScript Design Patterns (free to read online!) by Addy Osmani looks to be going a lot deeper down this rabbit hole.
You should probably remove the “function()” from the second line of every code example (except the first and last ones). :-)
Doh! Fixed.
Great explanation, man…
Awesome sauce. Pretty similar to what I have been doing but cleaner. I really like how to do the settings. Thanks
I’d recommend looking into Marionette (http://marionettejs.com/). I like using their modules/views/routers/controllers even if I’m not using Backbone to interact with a REST back end. Marionette gives me a sane way to structure code. It also takes care of some of the boilerplate code and memory management issues.
The developer Derick Bailey also gives a nice JSFiddle to get you started (http://jsfiddle.net/derickbailey/M5J8Q/). It’s uber simplified but a good starting point if you want to learn/dabble.
If you use that same “s” variable for the settings for each module, and then import them all into the same global.js, wouldn’t they conflict with each other?
That is a good catch IMHO, they’d better use some module loader (require.js or equivalent) or use an auto-executing function ( the
to enclose local variables.
They’d rather use an existing module pattern (once again, AMD style) then re-coding it.
No, because the modules are initialized sequentially. But I would use ‘this.settings’ (or local shortcut var, if I need ‘this.settings’ many times) in place of ‘s’.
@atmin That’s what got me too.. why pollute the global namespace for a shortcut? Why not set the s var local and use it as a shortcut, or just skip the semantics and use s as the settings object?
Fine, they’re initialized sequentially. But I thought the reason that
s
was declared outside the module instead of as a local variable inside theinit
function was so other methods in the same module could more easily access the settings in the future. IfNewsWidget.getMoreArticles
referencess
, it’s going to be looking at the wrong settings.Actually, I think in the example code, inside the event handler, that would probably throw an error because it references
s.numArticles
and would be triggered after other modules had been initialized.Here’s an example of what I’m talking about: http://codepen.io/jetpacmonkey/pen/gkmei
Agree with Michael generally. I used to write my modules like demonstrated in the post and quickly ran into name collision issues. I now write my modules using the self-executing function pattern, thus providing “encapsulation” for private variables/methods/etc to the module. Try something like:
FWIW, Indentation doesn’t seem to be working properly…or I’m missing something about how to format code in a <pre>
What Brendan said :)
The indentation is fine. The preview seems to be broken.
Global variables are one of the worst anti-patterns in any programming language. This is almost always the first thing you are taught in a CS-101 course at any university. JavaScript makes using this anti-pattern easy and almost goads you into it. Why? Because you often find yourself in the middle of a closure scope with no way of accessing a variable you need, so you make a variable in an outer scope. Chris said it himself, “we’ll make the settings available to each of them [sub-functions].” The best thing that you can do to your global-scope variables is to declare them “const” and make them immutable. If JS starts yelling at you about illegal access, you know you are using it incorrectly. The other solutions are listed in some of the other comments. Use namespacing.
Something seems strange with your module pattern: you declare the settings object, and assign articleList to a jQuery object. That means that your DOM has to be ready when you include this javascript file. If that’s true, what’s the purpose of having an init function that bind events to the DOM ?
Load all scripts at the bottom, DOM is ready when you call the script.
It would probably be more flexible if instead of having a fixed ID for the list of articles, it could be passed as a parameter to init()
Agreed. Exactly what I do, but I do like to have default value that I can override.
Jeremy: I believe that this wouldn’t happen. The ‘s’ is also referencing ‘this’ which, I believe, keeps things from over-writing one another thanks to the lexical scope of functions. Of course, if I’m wrong, I stand corrected.
the
this
is on the right side of the equals. Thes
variable that’s actually being assigned to has global scope (which was the whole reason that it was declared outside of the module), which means, unless Ruby on Rails is doing something fancy, the second module’sinit
would overwrite the settings from the first, and any later calls to a function inside the first module that usess
would be referencing the settings for the second module.Could this also be written like this? `
More OOP I guess?
I think that yes, it could be written like that. Chris’ example focuses on stricter namespacing. Where ‘NewsWidget’ is a master class with sub-classes attached to it: ‘settings’, ‘init’, etc.
Actually the methodology which Chris has used conforms Singleton design pattern & it’s very commonly used amongst OOP languages.
You can look on internet for situations where exactly you are supposed to use it.
Thanks for mentioning my post, Chris.
For those interested, I highly recommend a few of the comments posted on mine, which gave some great suggestions. I particularly liked the one from Maciej Baron:
http://www.impressivewebs.com/my-current-javascript-design-pattern/#comment-32835
Howza bout this –> http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
This is not Module Pattern, this is a simple Object Literal, Module Pattern is a bit more than that, and that bind function is not really a good way do develop, something like that: https://gist.github.com/4504091
I’ve made an Module Pattern bootstrap, check this out: https://github.com/guilhermepontes/module-pattern-bootstrap
there are lots of way to realize the Module Pattern,the Object literal is one of them.Your text to link here…refer to this
This gist represents a Module App: https://gist.github.com/4504159
I use similar approach but using function (due to autoinitialization). It can be easy adjusted to use it as a constructior:
The fact that you do not use the
var
keyword in front of _somePrivateMethod means that it gets put onto the global scope. Your example is pretty good, but in order for your method to truly be private, you will needvar
to keep the scope local.var _somePrivateMethod = function() { ... }
Nice catch, thanks.
Hi, take a look at updated example – in previous I’ve slipped a bit and in single instances (no ‘new’) ‘this’ points to ‘window’ object. Here are updated examples:
You can see it on jsFiddle:
* standard example (single, auto init) – http://jsfiddle.net/nightman/jxZ5n/1/
* example with multiple instances, no auto init – http://jsfiddle.net/nightman/B8ECk/1/
Regards
Karol – I like your implementation best.
Here is your example of the multiple instances version, but using auto-init.
http://jsfiddle.net/B8ECk/2/
Looks really nice! Thanks.
Hi Cooper, take a look at updated example – in previous I’ve slipped a bit and in single instances (no ‘new’) ‘this’ points to ‘window’ object. Here are updated examples:
Regards
Thanks for sharing, i use the same method but as a singleton , have look at this :
http://robdodson.me/blog/2012/08/08/javascript-design-patterns-singleton/
I’m nowhere near being a JS pro. I did learn about this pattern from a few coworkers when we were working for a big client about 6 months ago. Since that time, this is how I architect all of my JS. There’s quite a few benefits to it: 1) You can store each module separately in your CMS,and concatenate upon build. 2) If you’ve written modular HTML and CSS, you can pair functional modules with presentation modules. 3) when you use the pattern consistently, it’s easy to create JSON with it.
The ‘Advanced’ approach which I learned is that you can create an object representing all your modules and assign it to the window, and then create a ‘master’ init to run your modules on document ready.
window.paceaux = {
this.init = function(){
NewsWidget.init();
ArticleWidget.init();
},
NewsWidget ={
//blah code
this.init= function (){
}
},
ArticleWidget= {
this.init = function (){
}
}
};
//———–
//Document ready
//
$(function () {
window.paceaux.init();
});
The main problem with this is that it’s very monolithic in that it has hard-coded dependencies on the DOM, it is a singleton so you cannot have multiple widgets per page, and it would be difficult to test.
The style I personally favour for these type of things is the style you see in the bootstrap plugins. That is:
you wrap everything in a self-invoking function
inside that have a constructible object which has all the widget’s logic.
dependencies are passed into constructor, meaning unit testing becomes much easier and you have can multiple widgets per page
You can also very simply create a jQuery plugin and declarative data-* API from this because all your logic is wrapped in a neat object. It’s basically boilerplate code, and it makes things very flexible.
I’ve prepared an example fully working widget, which shows exactly what I mean on codepen. It’s heavily commented in the JS so everyone should be able to follow along. It demos multiple widgets on one page too :)
awesome, I hope there will be more of this discussion..
theres a lot of js pattern that can be used although sometimes we should know it make sense to use a pattern
Your structure is correct, but it needs a few more things before it’s really a module, i.e. encapsulating private members, exposing a public API and namespacing. I highly recommend you read the original module pattern post by Douglas Crockford.
In essence you will have a self-executing function with private members:
…that exposes with a public API:
…that can be enabled on DOM load like this:
or like this if
_init
accepts parameters:This seems like a simple way to begin to wrap my head around writing modularized code.
Also, I hadn’t seen Addy’s book, thanks for the reference!
small typo:
You forgot an “S” in Addy’s last name.
May I suggest you to look at BEM methodology.
BEM is a way to organize your code to simplify process of development and future support.
There also was a set of articles about BEM at SmashingMagazine. And project structure was described at part 3.
This looks like a good way to code.
The
{ spam: eggs }
looks like a dictionary to me.Does this wok with pure JS?
That was excellent ! just as always …
I have some things similar but this is how at the moment I do mine, if bad, better ways etc please feel free to advise.
Chris, I give you an “A” for effort, and a “B-” for execution.
As others have pointed out, the “s” variable will be global, and thus runs the risk of being trampled by other modules. It’s also not a true module pattern. Assuming you want it to be a singleton, you could modify your example slightly to this (which is similar to some of the other posts in the comments):
I think as long as he wraps the entire thing in a self-executing anonymous function, then there’s no concern about the global “s”. And that would be similar to your proposal above (which I like BTW).
Excellent, Peter. Clean, and works well. I will follow this pattern myself with future code!
If the entire thing is wrapped in a self executing anonymous function, then “s” would not be global, but then neither would NewsWidget, meaning he couldn’t call NewsWidget.init() outside of the self executing function. The work around would be to declare NewsWidget without “var” which would implicitly create it as a global, but I would generally discourage that.
Instead of wrapping the entire thing in a self executing anonymous function, I’ve basically kept the anonymous function but have it returning an object (and then I assign that to NewsWidget). It’s similar, but this subtle change makes a big difference.
I guess the way I’m looking at it is that this would be the structure for the entire JS for a single site/app. Therefore, it wouldn’t matter that “s” is global to the application, or that the main object is not accessible outside the function. Especially if it’s a small app that isn’t going to have any potential conflicts and whatnot.
I like this because it fixes the settings variable being global, but how would I use this with the module pattern using closures to make functions private/public (encapsulation). If every function is in the return, it will be public. If you move functions out of the return, you’ll make them private but lose access to the settings var.
@Jerry, If you move functions out of the return, you’ll make them private. You’ll still have access to the settings via the private “s” variable. For example:
In that example, I’ve added a private method, “somePrivateFunction”, which has access to the settings via the private variable “s”. Alternatively, I could have done something like take a reference to “this” as one of the parameters:
And then where I call the private function:
Very nice Peter. I am currently experimenting with this modular pattern also!
Another way to achieve this is.
Great article! I have worked with codes following those patterns, but I had some doubts. Thanks.
Great explanation, man. Happy to read it :)
Great bit of explanation to write scripts based on patterns. Much needed guidelines to avoid any errors while writing a script.
Hi, I think you meant Addy Osmani !
Great article !
Cheers
Good read, I also agree with comments made by Peter Foti above. I think you would fall in love with Sparky.js if you took a look – http://sparkyjs.com/
I’m not a pro at JS, but my javascript “a ha” moment came with the revealing module pattern:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
I agree with the author that it’s an improvement. I had done a little bit of OOP (such as it is) in PHP so having an object with public and private methods clicked for me.
Great little article about the module pattern! I’ve really been getting into it lately, with the Rails asset pipeline and trying to organise our mess of JavaScript at work using require.js. It makes everything much neater IMO, and I love having files with just a couple of hundred lines of JS rather than a couple of thousand.
Thanks Chris …
Honestly, you just scratched the surface of closure logics. It took me some time to get behind those secrets, but once understood the whole closure subject reveils the pros of JS programming.
Just expand the term “module” and think in terms of “frameworks”. Build your own libraries and use them consistently.
One example:
You use a variable outside of your module. How nice would it be to utilize pure “private” variables, only accessible from inside the module?
The master science is to keep a reference inside the module which points to itself in any context. No ,”this” doesn’t help since it points to other objects when a module function is called from an event handler or a timer.
There are a lot of docs and examples around, and I can only encourage everyone to increase their knowledge – Its’s worth it, and it will turn your ACME Javascript into a versatile programming language.
From what I understand about patterns, this is not a Module pattern, but a simple Singleton pattern. Singletons are defined by their simple construction via the object literal syntax. They commonly lack encapsulation as everything (properties and methods) is usually exposed and accessible publicly.
Because of this “everything is exposed” it opens the object up to mutation. In multiple dev environments or public API’s this is usually not good form and encapsulation is more desirable.
Encapsulation, what a singleton usually lacks, is what provides a controlled API where you only expose privileged methods that have access to the private variables. This prevents accidental overwriting and mutation.
Modules on the other hand, are built with the purpose of providing encapsulation. The basic Module is a function that returns a privileged function or an object with privileged methods that have access to private variables, but the catch is these variables that contain the data are not a part of the retuned object, so they are not exposed publicly, outside of the module function.
If you’re thinking, “that sounds like a closure”, it is! This closure allows the developer to control what and how the data is accessed, e.g. encapsulation. This is best form for public API’s and multiple development teams.
TL;DR
Singletons are defined by an object literal syntax and don’t normally have encapsulation with private and privileged entities:
Modules on the other hand are defined by a function returning an object with privileged methods having access to private variables:
At least, this is how I understand patterns in JavaScript. Let me know if I’m misunderstanding something here.
I was going to jump in and mention that this isn’t really a module pattern but a singleton but Justin Lowry beat me to it. I don’t like to get religious on patterns and programming techniques because a lot of times it’s just semantics or differences in background. There can be singleton modules, instantiable modules, modules that have factories inside, etc.
In this case, the code samples are def. singletons. There’s nothing wrong with singletons but for those not paying attention to what is going on…it could cause memory leaks if you’re not manually managing what the object is referencing.
Till the middle of comments list I was afraid nobody would have mentioned the AMD (Asynchronous Module Definition).
Of course, the Singleton pattern shown in the article usually would fit needs of the most developers. But a bit more complex web-apps consisting of many sub-modules with various dependencies are pain in the a…
I’ve come from PHP World into the JavaScript-driven apps and some things went out quite weird. But when I started learning the AMD-approach, developing an app started to enjoy me due to whole process.
Somebody wrote earlier about private variables. Huh, there’s some problems indeed. I solved that situation using build scripts which analyze content of my source code, for example this._somePrivateStuff() is being rewritten to simple var _somePrivateStuff() and further parsed. Why so weird? Huh, I’ve been googling and reading many docs about TDD in JS and one thing was sad – absolutely no reflection mechanisms at all. So that – in development version you should make your private/protected variables… public but prefixed and just before release – replace declarations with proper modifiers.
If someone has better experience for designing such modules regarding the TDD approach, feel free to respond on this comment.
I’m not sure how deep your knowledge of JS goes, but privacy can only be created by using function scope to close over the variables (i.e. closure), hiding them from the outside scope. Prefixing variables with the underscore does absolutely nothing functionally.
If you’re developing a complex JS app, and you are wanting to test it, the best way is to use an actual Module or Factory pattern and have it return the methods you desire without returning the private variables. Then, you can have the testing framework test the API and ensure that it returns what’s expected.
One of the best JS frameworks that has gorgeous built in unit testing is AngularJS. They’ve built the whole framework with testing in mind. I highly recommend looking into it and discovering how they went about solving problems.
They’ve even create dependency injection (DI) that makes testing nearly effortless. DI is rarely found but a very powerful way of handling dependencies.
Anyway, if you desire true privacy, you can’t use what you know about other “classical” languages, and you have to really understand the prototypal nature of JS and its lexical scoping. If you try to impose more classical styles to JS, you’ll get bitten in the end.
Uhm, my bad – of course those variables are enclosed by closure. I meant accessing the private fields inside during testing because – AFAIK – no JS VM has something like reflection abilities.
I’ll look at AngularJS, thx for feedback.
As others have stated this is actually not The Module Pattern, it’s the Singleton (Object Literal Pattern). Rebecca Murphey has a really great post about this pattern in case anyone wants to learn more about it : http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/
Awesome stuff, thanks Chris.
Amazing explanation on module pattern design now only if we had a 20 page book that focus on module design pattern and different approaches. Andy Osami books are great but he explains all the patterns and Module pattern is the most popular.
i wanted to ask if i subscribe to lodge,can i learn server side techniques like automatically adding up new feeds on the home page just like this site’s homepage and how to handle forums n all ??? i am a beginner in all this stuff(confused).
Love this pattern and have been using a flavor of it for awhile now.
Quick tip: In the bind_events method, .on() has the ability to pass in event.data. This means that you don’t necessarily need to wrap a function call inside of another function just to pass arguments.
A snippet from one of my bind_events methods.
Notice the JSON object parameter in some of these bindings. { index: 1 } can later be accessed inside of the said function via something like…
Better? Not necessarily. Just another tool in the belt.
The event.data tip is very cool. I use .on() constantly and never knew this trick. Very cool. Thanks for sharing.
This is a cool pattern, but I’d only use this for passing objects that have been generated on the fly. If you just want to execute a method on an object as a callback, personally I prefer using
$.proxy
.e.g. using Chris’ code above:
Saves us needing the extra
s
varHi, I’ve slipped a bit in previous code samples – in my example of single instance “this” point to “window” object. Here’s updated version:
jsFiddle code:
* http://jsfiddle.net/nightman/ynUZf/ – single instance, basic example
* http://jsfiddle.net/nightman/3kzhj/ – single instance, example with additional options
* http://jsfiddle.net/nightman/TBKvB/1/ – multiple instances (constructor example)
* http://jsfiddle.net/nightman/prpU2/2/ – multiple instances (constructor example) with auto init
Regards.
Be careful. There are many people that write about JavaScript, that are not experts (not talking about you, but who we get our information from). I’d bet there are more novice programmers churning out JavaScript than any other language, leading to a proliferation of plug and pray widgets and libraries.
Programming is not just about learning the syntax of a language and forging ahead, that’s experimentation (nothing wrong with that, just don’t use it as an example of the best way to do it). Programming is also not just about communicating with a computer, or learning algorithms and patterns. What’s also important, especially these days, is that it is about communication with humans, and showing a fellow developer what your program does (even yourself, especially once your memory has lost its mental model of your program).
There are many JavaScript ‘best practice’ articles and coding standards that focus on writing for the compiler, not the author. Programming itself (in the abstract sense I suppose) is a skill which is very difficult to transfer to others, learning syntax, algorithms and patterns is the easy part.
Bret Victor touches on this, and a lot more in his wonderful essay: http://worrydream.com/#!/LearnableProgramming if you have the time to read it, it’s rather long, but an absolute joy.
A good module would not allow that
settings
object to be manipulated directly from outside the module, they would be private to the module, and only be modifiable from outside if a public function existed to allow it. That way, it can be validated, what if somebody dids.numArticles = document.location.search.substring(1)
?A great module would not just have programmatic access to settings, there would be a way to retrieve all the parameters it needs from the document. You shouldn’t be writing JavaScript modules for JavaScript programmers, you should be writing for HTML authors, especially if you want more people to use them, they just want to write the HTML to include your script and for that to be the end of the matter.
On top of this, an awesome module would not have any HTML IDs hardcoded, anywhere. It would inspect the document and discover whether itself was required and act accordingly, pretty much like how polyfills work, using elements, classes, microdata, anything but HTML IDs.
Your ‘module’ is a merely an object created using the object literal syntax. The reason you need to export your reference to
settings
is that you haven’t actually used the module pattern from that book: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript – the book starts the module pattern by describing the object literal syntax as a prerequisite, then goes on to describe the module pattern itself. The object literal is a way of creating an object without usingnew Object()
like the string literal creates a string without usingnew String()
.That book looks pretty good. At least it knows uses the correct terminology for Immediately Invoked Functions, unlike quite a few of the previous comments, who are still calling them self-executing. This function is self-executing:
Self Executing functions belong to discussions about recursion. This function is invoked immediately:
Although I prefer to use the
new
keyword personally:No trailing parenthesis are required, and you don’t have to
return
the module’s interface, just use the new object (this
) to define it.Why you have
NewsWidget.init(); SomeOtherModule.init();
within an Immediately Invoked Function Expression, I’ll never know. Since you have nothing in there to protect or make private. Still, if the modules themselves were invoked immediately, then you wouldn’t need to callinit
on them at all.Nice summary and really thought topic. Thanks!
@Lee, great response, thanks. I was losing faith reading this post & comments. +1 for knowing what the hell you’re doing.
This is awesome. Thank you for sharing your expertise.
I took this and extended it with options. Thanks to @karol with the example from his method.
CodePen: Module Pattern with options object
s.moreButton.on click event never get triggered, does anyone tell me why?
if I use $(“#more-button”) instead, it will work
I’ve just recently begun to use a modification of this pattern. I like using objects this way, but I don’t like how hard it gets to make sense of sub-objects as code gets more and more complex. I also feel fairly strongly about using full words as variable names in any case where it’s possible. I find that it’s much more self-documenting. My code ends up looking more like this:
I guess I could also start using the “settings” portion as default settings, and then passing in a “settings” object to the initialize function to overwrite select defaults. I’m sure there are lots of other things that could be better, but this is the way my pattern is right now. I like that even though I’m working with an object, I don’t have to wonder as much about where sub objects end, and if they’re commented right.
I love this style of coding in your example. It’s much cleaner to me. But looking at the other styles in the comments got me looking at a small fullscreen module I wrote a couple days ago and I realized every method in the module is public. I would love to stick with this style if it is possible to make methods private.
So I suppose the way others have done it is better. I was wondering one thing though. Is it necessary or good practice to pass in window in a self invoking function like this example? I know jquery plugins do it in case ‘$’ gets overwritten by another script but will ‘window’ ever get overwritten?
Makes more sense to me after reading more of the comments and finding this link from Oriely. The part about modules with constructors also answers another question I had about how to pass options into a module.
How to use the module pattern
Nice article, there is just one thing what I would change…
var s;
You should declare the “s” variable inside the private scope of init, cause you create a global s variable with “undefined”. It’s always better to keep global variables to a minimum.
Nice article!
I have been using a closure that Christian Heilmann talks about in his article, Seven JavaScript Things I Wish I Knew Much Earlier In My Career, called “the revealing module pattern” and found it to be working well. I was actually thinking about closure in your very first code snippet of this article and I haven’t tried using an object for closure. I guess everyone have their own style but which way is generally the best?
Wow ty for that link :)
You should give a look at
Terrific JS
Nice article. I have been writing Javascript apps for a while and have been frustrated with how difficult it is to structure apps. I ended up making my own Javascript app structuring program called structureJS https://github.com/ShamariFeaster/structureJS
More module approach is your using clean JS
}
;(function(){
})();
This does not appear to be an actual example of Module Pattern design? You are simply assigning an object literal to a variable… Module Pattern must use an anonymous function that executes inline to create a closure on the namespace you are creating. This allows for public/private members which mimics OOP