Created
January 11, 2016 16:07
-
-
Save gregrickaby/8fb455da878111758843 to your computer and use it in GitHub Desktop.
Creating a global Js Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create an object in the global scope, pass in window, jQuery, and the global object into the anonymous function. | |
window.myObject = ( function( window, $, myObject ) { | |
// Create our object, properties, and functions. | |
myObject = { | |
window: $( window ), // Remove if you don't need it, makes your object smaller. | |
// Access variables using myObject.options | |
options { | |
loadedText: 'myObject loaded.', // Loaded message for when you first add, remove once you know it's loading. | |
}, | |
// First function loaded in this object. | |
__construct: function() { | |
console.log( myObject.options.loadedText ); // Remove once you know your object is loading. | |
// Bind things. | |
$( '.my-thing' ).on( 'click', myObject.myFunction ); // Don't have to pass event, jQuery does that. | |
}, | |
myFunction( event ) { | |
// Do something. | |
} | |
}; | |
$( myObject.__construct ); // Load the object's first function. | |
return myObject; // Return the object to window.myObject so it can all be accessed from the global scope. | |
} ) ( window, jQuery, window.myObject ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment