Skip to content

Making your first JS component

Jonathan Garbee edited this page Nov 18, 2016 · 4 revisions

First, make your components object. Each object will be given the element it is targeted against. This will allow you to modify that element within your object.

function Dropdown(element) {
    'use strict';
    this.element_ = element;
    this.init();
}

Next, create the init method on your object's prototype.

Dropdown.prototype.init = function() {
    "use strict";
    this.boundClickHandler = this.clickHandler.bind(this);
    this.element_.addEventListener('click', this.boundClickHandler);
};

In this case, we are assigning an event listener to the element. So, now go create that handler on the same prototype.

Dropdown.prototype.clickHandler = function(event) {
    "use strict";
    var target = event.target;
    if( ! target.classList.contains(this.CssClasses_.DROPDOWN_IS_ACTIVE)){
        target.classList.add(this.CssClasses_.DROPDOWN_IS_ACTIVE);
        target.nextElementSibling.classList.add(this.CssClasses_.DROPDOWN_IS_ACTIVE);
    } else {
        target.nextElementSibling.classList.remove(this.CssClasses_.DROPDOWN_IS_ACTIVE);
        target.classList.remove(this.CssClasses_.DROPDOWN_IS_ACTIVE);
    }
};

Now go add CssClasses_ to the prototype. This will be a standard object to grab strings from.

Dropdown.prototype.CssClasses_ = {
    DROPDOWN_IS_ACTIVE: 'dropdown-is-active'
};

Finally, just register the component with the componentHandler provided by MDL.

componentHandler.register({
    constructor: Dropdown,
    classAsString: 'Dropdown',
    cssClass: 'js-dropdown'
});

All done. Now the following markup will automatically be turned into a dropdown menu (provided proper styling):

<nav class="mdl-navigation">
    <a class="mdl-navigation__link js-dropdown">Header Item</a>
    <div class="mdl-navigation__dropdown">
        <a class="mdl-navigation__link" href="#">That thing you wanted</a>
        <a class="mdl-navigation__link" href="#">Another thing</a>
    </div>
</nav>