Skip to content

Instantly share code, notes, and snippets.

@gregrickaby
Created January 11, 2016 16:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gregrickaby/8fb455da878111758843 to your computer and use it in GitHub Desktop.
Save gregrickaby/8fb455da878111758843 to your computer and use it in GitHub Desktop.
Creating a global Js Object
// 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