Skip to content

Instantly share code, notes, and snippets.

@jhafner
Created June 6, 2013 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhafner/5722774 to your computer and use it in GitHub Desktop.
Save jhafner/5722774 to your computer and use it in GitHub Desktop.
Basic example of Object-Oriented JS
function Element($el) {
// The jquery obj for the dom element represented
this.$el = $el;
// Other object properties used by the object
this.$trigger = $el.closest('.trigger');
this.openClass = 'js-active';
// Object functions to be called on object instantiation
this.init();
}
Element.prototype = {
constructor : Element,
// Initializes the object state
init : function() {
// `thiss` used to maintain reference to this object, when
// `this` will be in a different scope later
var thiss = this;
this.$trigger.click(function(e){
thiss.hasClass(thiss.openClass) ? thiss.hide() : thiss.show();
});
},
// Other functions to make object functional
// modular, and reusable
hide : function() {
this.$el.fadeOut();
this.toggleClass(this.openClass);
},
show : function() {
this.$el.fadeIn();
this.toggleClass(this.openClass);
}
}
//In some other file, this is how you'd call the above:
$(".element").each( function() {
var element = new Element($(this));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment