JavaScript Module - Constructur and Prototype
JavaScript Module - Constructur and Prototype
by Nirvanachain
HTML
<div class="js-container">
<div class="js-content">
<p class="js-paragraph">Hide/show this text when the link is clicked.</p>
<a href="#" class="js-link">Click Here</a>
</div>
<div class="js-moreContent">
Change text color.
</div>
</div>
JavaScript
/*
* Toggle has been created to demonstrate the use
* of prototype and constructors. A click event is used
* used to toggle the visibility of text in an element
* with a class of '.js-paragraph.' It will also change
* the color of text in the element with a class of
* '.js-moreContent'.
*/
(function () {
var MyToggle = function ($element) {
/*
* Reference to the main element
*/
this.$element = $element;
/*
* Set up a reference to constants which will be used later
*/
this.CONTENT = '.js-content';
this.PARA = '.js-paragraph';
this.LINK = '.js-link';
this.MORECONTENT = '.js-moreContent';
/*
* Flag for changing text color
*/
this.isRed = false;
this.init();
};
/*
* Initialize the Toggle class. Creates child
* references. Attaches event handlers, and
* enables to the module.
*
* @method init
* @return Toggle
*/
MyToggle.prototype.init = function () {
this
.createChildren()
.setupHandlers()
.enable();
return this;
};
/*
* Create cached jQuery selectors.
*
* @method createChildren
* @return Toggle
*/
MyToggle.prototype.createChildren = function () {
this.$content = this.$element.find(this.CONTENT);
this.$para = this.$element.find(this.PARA);
this.$link = this.$element.find(this.LINK);
this.$moreContent = this.$element.find(this.MORECONTENT);
return this;
};
/*
* Bind the context of the module to the
* onClick method.
*
* @method setupHandlers
* @return Toggle
*/
MyToggle.prototype.setupHandlers = function () {
this.onClickHandler = this.onClick.bind(this);
return this;
};
/*
* Attach events and enable the module
*
* @method...