国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Create a framework for the library
A brief discussion of concepts
Return to encoding
Using text and HTML
Operation Class
Use Properties
Create elements
Attached and prefixed elements
Delete elements
Usage Events
Usage library
That's it!
Home Web Front-end JS Tutorial Build Your First JavaScript Library

Build Your First JavaScript Library

Mar 11, 2025 am 12:09 AM

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 functional 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 purpose 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. Create a framework for the library

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 a length property, we will know that we have a list of nodes. We will store these elements in this.elements , Dome object can wrap multiple DOM elements, 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 takes a parameter, a callback function. We will loop through the items in the array and collect the content returned by the callback function. 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".

A brief discussion of concepts

If building a library is just writing code, it wouldn't 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.

Return to 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. Using 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 the 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 want to be able to add and delete classes, so let's write addClass and removeClass methods.

Our addClass method will use 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);
        }
    });
}

Very simple, right?

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

  1. Use Properties

Next, let's add the attr function. This will be easy as 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 getAttribute method.

  1. Create elements

We should be able to create new elements, and any good library can do that. Of course, this is meaningless as a method of 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 Dome object through text method. Here are the actual actions for all of them:

 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 the 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. Attached and prefixed elements

Next, we will write 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
  • An 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 it 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 elements

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 iterate, I will use the removeChild method to reverse iterate the loop, and Dome object for 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. Usage Events

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

Check out 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 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. Usage 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 little 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 digging 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've learned from jQuery source code (Paul Irish)
  • Behind the Scenes of jQuery (James Padolsey)
  • React 16: Deep in the API compatibility rewrite of 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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which Comment Symbols to Use in JavaScript: A Clear Explanation Which Comment Symbols to Use in JavaScript: A Clear Explanation Jun 12, 2025 am 10:27 AM

In JavaScript, choosing a single-line comment (//) or a multi-line comment (//) depends on the purpose and project requirements of the comment: 1. Use single-line comments for quick and inline interpretation; 2. Use multi-line comments for detailed documentation; 3. Maintain the consistency of the comment style; 4. Avoid over-annotation; 5. Ensure that the comments are updated synchronously with the code. Choosing the right annotation style can help improve the readability and maintainability of your code.

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

Mastering JavaScript Comments: A Comprehensive Guide Mastering JavaScript Comments: A Comprehensive Guide Jun 14, 2025 am 12:11 AM

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScript Data Types: A Deep Dive JavaScript Data Types: A Deep Dive Jun 13, 2025 am 12:10 AM

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

See all articles