Home >Web Front-end >JS Tutorial >Build Your First JavaScript Library

Build Your First JavaScript Library

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-03-11 00:09:09626browse

Build Your First JavaScript Library

Have you ever been amazed at the magic of React? Ever wondered how Dojo works? Have you ever been curious about jQuery's clever operation? In this tutorial, we will sneak behind the scenes and try to build a super-simplified version of jQuery.

We use JavaScript libraries almost every day. Whether it is implementing algorithms, providing API abstractions, or manipulating DOMs, libraries perform many functions on most modern websites.

In this tutorial, we will try to build a library like this from scratch (this is a simplified version of course). We will create a library for DOM operations, similar to jQuery. Yes, it's fun, but before you get excited, let me clarify a few points:

  • This won't be a fully featured library. We're going to write a solid set of methods, but this is not a complete jQuery. We will do enough to give you a good understanding of the types of problems you will encounter when building libraries.
  • We are not pursuing full compatibility across all browsers here. The code we wrote today should run on Chrome, Firefox, and Safari, but may not work on older browsers such as IE.
  • We will not cover every possible use of our library. For example, our prepend methods are only valid when you pass them our library instances; they do not work with original DOM nodes or node lists.

  1. Framework for creating libraries

We will start with the module itself. We will use the ECMAScript module (ESM), a modern way to import and export code on the web.

export class Dome { constructor(selector) { } }

As you can see, we export a class called Dome, whose constructor will accept a parameter, but it can be of multiple types. If it is a string, we will assume it is a CSS selector, but we can also accept the results of a single DOM node or document.querySelectorAll to simplify element search. If it has the length attribute, we will know that we have a list of nodes. We will store these elements in this.elements, the Dome object can wrap multiple DOM elements, and we need to loop through each element in almost every method, so these utilities will be very convenient.

Let's start with a map function that accepts a parameter and a callback function. We will loop through the items in the array and collect the content returned by the callback function. The Dome instance will receive two parameters: the current element and the index number.

We also need a forEach method, by default, we can simply forward the call to mapOne. It's easy to see what this function does, but the real question is, why do we need it? This takes a little bit of what you might call the "library concept".

Brief discussion of concept

If building a library is just writing code, it would not be too difficult to do. But when working on this project, the harder part I found was deciding how certain methods should work.

Soon we will build a Dome object that wraps multiple DOM nodes ($("li").text()), and you will get a single string containing all the element texts concatenated together. Is this useful? I don't think so, but I don't know what a better return value is.

For this project, I will return the text of multiple elements as an array unless there is only one item in the array; then we will return only the text string, not the array containing a single item. I think you get text for a single element the most often, so we optimized for this situation. However, if you are getting text for multiple elements, we will return what you can use.

Returns encoding

So, mapOne will first call map and then return a single item in the array or array. If you're still unsure how this works, stay tuned: You'll see!

mapOne(callback) { const m = this.map(callback); return m.length > 1 ? m : m[0]; };
  1. Use text and HTML

Next, let's add the text method to see if we are setting or getting. Note that this is just iterating over the elements and setting their text. If we are getting, we will return the mapOne method of the element: if we are working on multiple elements, this will return an array; otherwise, it will be just a string.

html method is almost the same as text method, except that it will use innerHTML.

html(html) { if (typeof html !== "undefined") { this.forEach(function (el) { el.innerHTML = html; }); return this; } else { return this.mapOne(function (el) { return el.innerHTML; }); } } }

Like I said: almost the same.


  1. Operation Class

Next, we need to be able to add and delete classes, so let's write the addClass and removeClass methods.

Our addClass method will use the classList.add method on each element. When passing a string, only that class is added, and when passing an array we will iterate over the array and add all the classes contained therein.

addClass(classes) { return this.forEach(function (el) { if (typeof classes !== "string") { for (const elClass of classes) { el.classList.add(elClass); } } else { el.classList.add(classes); } }); }

It's very simple, right?

Now, what about deleting the class? For this you almost do the same thing, just use the classList.remove method.

  1. Using attributes

Next, let's add the attr function. This will be easy because it's almost the same as our html method. Like these methods, we will be able to get and set properties at the same time: we will accept one property name and value to set, and only one property name to get.

attr(attr, val) { if (typeof val !== "undefined") { return this.forEach(function (el) { el.setAttribute(attr, val); }); } else { return this.mapOne(function (el) { return el.getAttribute(attr); }); } } }

If val is defined, we will use the setAttribute method. Otherwise, we will use the getAttribute method.

  1. Create elements

We should be able to create new elements, and any good library can do this. Of course, this is meaningless as a method of the Dome class.

export function create(tagName,attrs) { }

As you can see, we will accept two parameters: the name of the element and the attribute object. Most properties will be applied through our attr method, and the text content will be applied to the Dome object through the text method. Here is how all of this is actually done:

export function create(tagName, attrs) { let el = new Dome([document.createElement(tagName)]); if (attrs) { for (let key in attrs) { if (attrs.hasOwnProperty(key)) { el.attr(key, attrs[key]); } } } return el; }

As you can see, we create an element and send it directly to the new Dome object.

But now we are creating new elements, we will want to insert them into the DOM, right?

  1. Add and preemption elements

Next, we will write the append and prepend methods. These functions are a bit tricky, mainly because there are multiple use cases. Here are the things we want to be able to do:

dome1.append(dome2); dome1.prepend(dome2);

We may want to attach or prefix:

  • A new element to one or more existing elements
  • Multiple new elements to one or more existing elements
  • A existing element to one or more existing elements
  • Multiple existing elements to one or more existing elements

I use "new" to represent elements that are not yet in the DOM; existing elements are already in the DOM. Let's explain step by step now:

append(els) { }

We expect els to be a Dome object. A complete DOM library will accept it as a node or a list of nodes, but we won't do that. We have to iterate through each of our elements, and then in it, we go through each element we want to attach.

If we are appending, the i from the external Dome object passed in as a parameter will only contain the original (uncloned) nodes. So if we append only a single element to a single element, all the nodes involved will be part of their respective prepend methods.

  1. Delete the element

For completeness, let's add a remove method. This will be very simple because we just need to use the removeChild method. To make things easier, we will use the forEach loop to reverse traversal, I will use the removeChild method to reverse traversal, and the Dome object of each element will still work properly; we can use whatever method we want, including appending or prefixing it back to the DOM. Not bad, right?

  1. Using events

Last but not least, we will write some event handler functions.

See the on method, and we'll discuss it:

on(evt, fn) { return this.forEach(function (el) { el.addEventListener(evt, fn, false); }); }

This is very simple. We just need to iterate over the elements and use the addEventListener method. The off function (it unhooked event handler) is almost the same:

off(evt, fn) { return this.forEach(function (el) { el.removeEventListener(evt, fn, false); }); }

  1. Using library

To use Dome, just put it in the script and import it.

import {Dome, create} from "./dome.js"

From there, you can use it like this:

new Dome("li") ...

Make sure that the script you import it is an ES module.

That's it!

I hope you can try our small library and even extend it a little bit. As I mentioned earlier, I've put it on GitHub. Feel free to fork it, play, and send pull requests.

Let me clarify again: The purpose of this tutorial is not to suggest that you should always write your own library. There is a dedicated team working together to make the large, mature library as good as possible. The purpose here is to give you some insight into what might happen inside the library; I hope you have learned some tips here.

I highly recommend you dig around in some of your favorite libraries. You will find that they are not as mysterious as you think, and you may learn a lot. Here are some good starting points:

  • 11 Things I Learned from jQuery Source Code (Paul Irish)
  • Behind the Scenes of jQuery (James Padolsey)
  • React 16: Deep Learning API Compatible Rewrite for Our Front-End UI Library

This post has been updated with Jacob Jackson's contribution. Jacob is a web developer, tech writer, freelancer and open source contributor.

The above is the detailed content of Build Your First JavaScript Library. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn