Created
June 6, 2013 16:13
-
-
Save jhafner/5722774 to your computer and use it in GitHub Desktop.
Basic example of Object-Oriented JS
This file contains hidden or 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
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