Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

4 Steps to Create Simple Reusable Javascript Components

INTRODUCTION
BE LAZY, REUSE.

Welcome to a tutorial on how to create reusable Javascript Components. Back in the school days, the first things that lecturers taught about object-oriented programming were code reusability… But the sad part is that they have never gone into the proper details of how to do it, despite preaching it over-and-over again.

So here it is, I have finally figured some things about being lazy and “reusability” after donkey years of being a web developer. In this guide, I shall share my “secrets” on building Reusable web and UI Components – With vanilla Javascript that is. Read on!

I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!

NAVIGATION
TABLE OF CONTENTS

Section A
The Basics

Section B
How to Build

Extra
Download & Future

Closing
What’s Next?

SECTION A
THE BASICS

Before we answer the question of “how to create reusable components”, let us take a look at the basics and ideas behind in this section.

WHAT ARE REUSABLE COMPONENTS?

If you have been writing functions, then you have already successfully created reusable components. Let us go through a very simple example, of let’s say, doing an AJAX call:

The raw sequential AJAX
// GET FORM DATA
var data = new FormData();
data.append('name', document.getElementById("form_name").value);
data.append('email', document.getElementById("form_email").value);

// THE AJAX CALL
var xhr = new XMLHttpRequest();
xhr.open('POST', "process.php", true);
xhr.onload = function(){
  // Do something
  console.log(this.response);
};
xhr.send(data);

Now, it will not make much sense to copy-paste that same piece of code over-and-over again for various different occasions. So the smart way is to “package” it into a function and reuse it:

The AJAX function
// The reusable AJAX call function
function ajacall (target, data, load) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', target, true);
  xhr.onload = function () {
    if (typeof(load) == "function") { load(this.response); }
  };
  xhr.send(data);
}

// You can now reuse the AJAX call function multiple times
var data = new FormData();
data.append('name', document.getElementById("form_name").value);
data.append('email', document.getElementById("form_email").value);
ajacall("process.php", data, function(res){ console.log(res); });

data = new FormData();
data.append('item', document.getElementById("form_item").value);
data.append('quantity', document.getElementById("form_qty").value);
ajacall("cart.php", data, function(res){ console.log(res); });

That, in a nutshell, is the most basic form of a reusable component – Where you “write once and use many times”. However, please take note that components are not just restricted to processes, it can also be UI components such as a date picker and time picker.

WHY CREATE REUSABLE COMPONENTS?

Well, I don’t think this needs much of an explanation.

  • Productive: An average newbie may take an entire month to complete a project, coding from scratch. But the smart code ninja who has built reusable components over the years can do it within just a week – Just because many parts of the code and components are already done.
  • Consistent: If you already have a component that is working well, it will work consistently well throughout all of your projects.
  • Less maintenance: Fixing one bug in your component equates to fixing the same bug in all your projects… Since they all use the same component. Upgrading is also a lot easier.

In a more business sense – Using reusable components cut down the development time, and thus, a lot more efficient and less costly. But of course, the main reason being, the lazy code ninja is also the smart one. Code once, use many times, same good results.

THE ESSENTIAL IDEAS

Some of you code ninjas may be thinking that creating components is difficult, and that you need to be some sort of a super hacker. Well, nope. On the contrary, we want the components to be as straightforward as possible.

  • Keep it simple: No complicated code, just simple functions, and UI… We are not building a time travel machine nor spaceship here.
  • Generic components: As with the above example, we only want “everyday coding stuff” like AJAX, fetching data from forms, and showing a “now loading” screen – These are the stuff that you can easily recycle and not use only once.
  • Abstraction: Put in X, and you get Y. That’s it, don’t have read through a thousand lines of code to understand what it does.
  • Standalone: Avoid jQuery, Angular, React, etc… Seriously, the whole idea is not to slow down the loading time by loading more libraries. Also, these 3rd party libraries may go obsolete over time, but vanilla Javascript will hardly ever go bad.

SECTION B
THE STEPS

The most “caveman” way to create reusable components is pretty much to write a thousand functions, and stash them into a single JS file… But let us take a look at a more elegant way of doing it – Of how I usually create my reusable components.

STEP 1) THE CORE SCRIPT

Start by creating a folder to keep all your components in. I just call mine “baseboxx”, because… why not? Then, create the core Javascript:

baseboxx/core.js
var _BB = {
  loadCSS : function (target) {
  // loadCSS() : load component CSS file
  // PARAM target : target CSS class

    var link  = document.createElement('link');
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'baseboxx/' + target;
    document.head.appendChild(link);
  }
};

As you can see, the core script is nothing more than a single _BB object. We will build our components on top of this object, and use the _loadCSS function to load the CSS for components that require some cosmetics.

STEP 2) GROUP YOUR FUNCTIONS

Next, you will want to map out all your functions and group the related ones together. For example, I may have a few functions in mind:

FunctionDescription
postAn AJAX call function to POST data to the server, and fetch the response.
fetchA function that builds upon post, puts the server response into an HTML container.
grabGets and formats form data.
blockShows a full screen “now loading”.
unblockHide the full screen “now loading”.

As you can probably see, it makes perfect absolute sense to group the related functions:

  • post, fetch, grab
  • block, unblock

STEP 3) BUILD YOUR LIBRARY COLLECTION

Now that you have grouped the functions together, let us create the actual component library for it.

baseboxx/ui.js
_BB.ui = {
  block : function () {
  // block : full page block

    document.getElementById("BB-Block").classList.add("show");
  },

  unblock : function () {
  // unblock : unblock page

    document.getElementById("BB-Block").classList.remove("show");
  }
};

// Add necessary HTML + CSS
document.addEventListener('DOMContentLoaded', function(){
  _BB.loadCSS("ui.css");
  var el = document.createElement('div');
  el.id = "BB-Block";
  document.body.appendChild(el);
});
baseboxx/ui.css
/* [BLOCK] */
#BB-Block {
  opacity: 0.7;
  background: #000;
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.5s;
}
#BB-Block.show {
  opacity: 0.7;
  visibility: visible;
}

See how we are “extending” the functionalities of the _BB object here? By simply building functions on top of it? We can do the same for the AJAX related components:

baseboxx/ajax.js
_BB.ajax = {
  post : function (target, data, load) {
  // post() : Do an AJAX call with POST data
  // PARAM target : target URL
  //       data : data to POST
  //       load : function to run on load

    let xhr = new XMLHttpRequest();
    xhr.open('POST', target, true);
    xhr.onload = function () {
      if (_BB.ui != undefined) { _BB.ui.unblock(); }
      if (typeof(load) == "function") { load(this.response); }
    };
    if (_BB.ui != undefined) { _BB.ui.block(); }
    xhr.send(data);
  },

  fetch : function (target, data, container) {
  // fetch() : fetch data from server and put into HTML container
  // PARAM target : target URL
  //       data : data to POST
  //       container : ID of target HTML container

    this.post(target, data, function(res){
      document.getElementById(container).innerHTML = res;
    });
  },

  grab : function (format) {
  // grab : get form data, format into provided KEY => VALUE
  // PARAM format : object in the format of KEY => ID OF ELEMENT

    var data = new FormData();
    for (let key in format) {
      data.append(key, document.getElementById(format[key]).value);
    }
    return data;
  }
};

STEP 4) USING THE COMPONENTS

Yep, the whole idea is to pretty much just to group the similar common functions into a component library, then include them as needed.

index.html



  
    Components Demo
  

Dummy form

Name:
Email:

Server Response

EXTRA
DOWNLOAD & THE FUTURE

That’s it for the examples and here is the download link to the scripts as promised. But please don’t take it as the “only correct way” to create components – There are plenty other gimmicks that you can explore, and I will list a few of them here.

JAVASCRIPT MODULES

As of ECMAScript 5, there has been a new “thing” called Javascript Modules, and it allows you to import/export Javascript functions and variables as modules. For example:

js-mod.js
export function foo() {
  alert('bar!')
}
module.html



  Module Demo

Will this become the “official way” to create modules and components? Maybe. But as exciting as this is, I will personally shy away from adopting Javascript module – To maintain backward compatibility with the older browsers and technologies.

POLYMER PROJECT

Hate to do all those complicated codes? Ever want to create your own HTML tags? Maybe, create a date picker just like a native HTML tag:

Yes, it is possible with the Polymer Project.

DOWNLOAD

Click here to download the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

CLOSING
WHAT’S NEXT?

We have come to the end of this guide, and I hope it has helped you to better understand how to create usable web and UI components. If you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!


The post 4 Steps to Create Simple Reusable Javascript Components appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

4 Steps to Create Simple Reusable Javascript Components

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×