Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
reply to post: Organizing events with jQuery
// -----------------------
// refactor by Miller Medeiros (
// of code samples present on blog post:
// -----------------------
//just so we make sure `myApp` does exist
window.myApp = window.myApp || {};
//no need to use `var` and it is actually wrong since we are setting a property
//of the object and not creating a new variable
//we also pass jQuery to the closure so we can use `$` without any issues
myApp.dashboard = (function($){
//in case you need to add extra functionality to your initializer we keep
//a concise and descriptive name for the initializer and keep all the logic
//in separate functions
function init(){
//loadEvents isn't a good name since you aren't "loading" anything, you are
//attaching the event listeners
function attachListeners(){
//no need to use `.delegate()` since we are attaching listeners to
//a single element
//name states that it is a click handler and which action will be
//performed, making it clear that it should be only called by a click
//handler and that it expects and Event object as parameter and that
//`this` will be bound to the element.
function selectOptionOnClick(evt){
//just to translate the parameters since `doSomething` expects an Element
//and it is on the exposed API, so we expect it to be accessed from outside
//our module.
function doSomethingOnClick(evt){
function doSomething(el){
//just a stub for some method of your module that will be accessed
//from inside your module and also from outside
//expose dashboard (PUBLIC API)
return {
init : init,
doSomething : doSomething
//pass jQuery to the closure so we can use `$` without issues (even if `jQuery.noConflict()`)
//initialize dashboard, note that we don't need to create an anonymous function
Copy link

millermedeiros commented Sep 2, 2011

Copy link

millermedeiros commented Sep 2, 2011

and more about the difference between each pattern: - and one of the the main advantages of using it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment