


Singleton mode in JS implements addition, deletion, modification and query of data
This article mainly introduces the implementation of JS based on the singleton mode (Singleton) in the design pattern to encapsulate the function of adding, deleting, modifying and checking data. Combined with the example form, it analyzes the correlation of javascript based on the singleton mode and ajax for adding, deleting, modifying and checking the database. For operational skills, friends in need can refer to
This article describes the example of JS based on the singleton pattern (Singleton) in the design pattern to encapsulate the function of adding, deleting, modifying and checking data. Share it with everyone for your reference, the details are as follows:
Single-case mode
The core structure of the single-case mode only contains one called A special class of singletons. The singleton pattern can ensure that a class in the system has only one instance.
The original definition of the singleton pattern appeared in "Design Patterns" (Addison Wesley, 1994): "Guarantee that a class has only one instance. And provide a global access point to access it."
Singleton pattern definition: "A class has one and only one instance, and it instantiates itself to provide it to the entire system. ”
var Singleton = (function(){ SingletonClass() { } var singleton = null; return { getInstance: function() { if (singleton == null) { singleton = new singletonClass(); } else { return singleton; } } } })(); Singleton.getIntance();
The front end often uses some asynchronous operations related to interfaces such as addition, deletion, modification and query. Let's take an example. When I operate a data list, I often add the modify and delete functions. Some solutions use synchronous (refresh the page), and the user experience is better using asynchronous;
The code is as follows
Add function
$(".add").click(function(){ $.ajax({ type: "post" dataType:"json", url: "http://www.jb51.net/", data: {name:"csdn博客",dir:"web前端"}, success: function( result ){ if ( result.status ) { alert("新增成功!") } else { alert("新增失败") } }, error: function(){ alert("新增出现异步,请得新增加或联系技术管理员"); } }); });
Delete function
$(".del").click(function(){ $.ajax({ type: "post" dataType:"json", url: "http://www.jb51.net/", data: {id:"1"}, success: function( result ){ if ( result.status ) { alert("删除成功!") } else { alert("删除失败") } }, error: function(){ alert("新增出现异步,请得新增加或联系技术管理员"); } }); });
The above two code snippets briefly describe the JS code for adding and deleting functions. Some students discovered that they have something in common, that is, part of the ajax requests are the same, and what if the delete function is also used in other places? , then you need to write the same code in other places. I feel very uncomfortable
Let’s improve it
var SingletonCRUD = (function(){ SingletonClass() {} SingletonClass.prototype = { constructor: SingletonClass, add: function( data ) { $.ajax({ type: "post" dataType:"json", url: "http://www.jb51.net/", data: data, success: function( result ){ if ( result.status ) { alert("新增成功!") } else { alert("新增失败") } }, error: function(){ alert("新增出现异步,请得新增加或联系技术管理员"); } }); }, remove: function( data ) { $.ajax({ type: "post" dataType:"json", url: "http://www.jb51.net/", data: data, success: function( result ){ if ( result.status ) { alert("删除成功!") } else { alert("删除失败") } }, error: function(){ alert("新增出现异步,请得新增加或联系技术管理员"); } }); } } var singleton = null; return { getInstance: function() { if (singleton == null) { singleton = new singletonClass(); } else { return singleton; } } } })(); var curd = SingletonCRUD.getIntance(); $(".add").click(function(){ var data = {"name":"name"}; curd.add( data ); }); $(".del").click(function(){ var data = {"id": 1}; curd.remove( data ); });
I often use Singleton instances to make some Tool tool classes;
The advantages of using design patterns: decoupling, strong readability, The code structure is clear;
Through the above small example, the acquisition data (click event function) and operation data (ajax request) in the click event are separated;
Through the singleton mode The optimized code:
var SingletonCRUD = (function(){ SingletonClass() {} SingletonClass.prototype = { constructor: SingletonClass, ajax: function(url, data success ){ $.ajax({ type: "post" dataType:"json", url: url, data: data, success: success, error: function(){ alert("新增出现异步,请得新增加或联系技术管理员"); } }); }, add: function( data ) { this.ajax("http://www.jb51.net/", data, function( result ){ if ( result.status ) { alert("新增成功!") } else { alert("新增失败") } }); }, remove: function( data ) { this.ajax("http://www.jb51.net/", data, function( result ){ if ( result.status ) { alert("删除成功!") } else { alert("删除失败") } }); } } var singleton = null; return { getInstance: function() { if (singleton == null) { singleton = new singletonClass(); } else { return singleton; } } } })();
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to use a child component to call a parent component in ES6
How to make a dynamic form in angular
Use $http to implement asynchronous uploading of Excel files in angularjs
The above is the detailed content of Singleton mode in JS implements addition, deletion, modification and query of data. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Last week, amid the internal wave of resignations and external criticism, OpenAI was plagued by internal and external troubles: - The infringement of the widow sister sparked global heated discussions - Employees signing "overlord clauses" were exposed one after another - Netizens listed Ultraman's "seven deadly sins" Rumors refuting: According to leaked information and documents obtained by Vox, OpenAI’s senior leadership, including Altman, was well aware of these equity recovery provisions and signed off on them. In addition, there is a serious and urgent issue facing OpenAI - AI safety. The recent departures of five security-related employees, including two of its most prominent employees, and the dissolution of the "Super Alignment" team have once again put OpenAI's security issues in the spotlight. Fortune magazine reported that OpenA

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

70B model, 1000 tokens can be generated in seconds, which translates into nearly 4000 characters! The researchers fine-tuned Llama3 and introduced an acceleration algorithm. Compared with the native version, the speed is 13 times faster! Not only is it fast, its performance on code rewriting tasks even surpasses GPT-4o. This achievement comes from anysphere, the team behind the popular AI programming artifact Cursor, and OpenAI also participated in the investment. You must know that on Groq, a well-known fast inference acceleration framework, the inference speed of 70BLlama3 is only more than 300 tokens per second. With the speed of Cursor, it can be said that it achieves near-instant complete code file editing. Some people call it a good guy, if you put Curs

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

According to news on June 26, at the opening ceremony of the 2024 World Mobile Communications Conference Shanghai (MWC Shanghai), China Mobile Chairman Yang Jie delivered a speech. He said that currently, human society is entering the fourth industrial revolution, which is dominated by information and deeply integrated with information and energy, that is, the "digital intelligence revolution", and the formation of new productive forces is accelerating. Yang Jie believes that from the "mechanization revolution" driven by steam engines, to the "electrification revolution" driven by electricity, internal combustion engines, etc., to the "information revolution" driven by computers and the Internet, each round of industrial revolution is based on "information and "Energy" is the main line, bringing productivity development

Unbelievably, in order to train an AI model, a professor from the State University of New York strapped a GoPro-like camera to his daughter’s head! Although it sounds incredible, this professor's behavior is actually well-founded. To train the complex neural network behind LLM, massive data is required. Is our current LLM training process necessarily the simplest and most efficient way? Certainly not! Scientists have discovered that in human toddlers, the brain absorbs water like a sponge, quickly forming a coherent worldview. Although LLM performs amazingly at times, over time, human children become smarter and more creative than the model! The secret of children mastering language. How to train LLM in a better way? When scientists are puzzled by the solution,

According to news from this site on July 11, the Economic Daily reported today (July 11) that Foxconn Group has entered the advanced packaging field, focusing on the current mainstream panel-level fan-out packaging (FOPLP) semiconductor solution. 1. Following its subsidiary Innolux, Sharp, invested by Foxconn Group, also announced its entry into Japan's panel-level fan-out packaging field and is expected to be put into production in 2026. Foxconn Group itself has sufficient influence in the AI field, and by making up for its shortcomings in advanced packaging, it can provide "one-stop" services to facilitate the acceptance of more AI product orders in the future. According to public information consulted on this site, Foxconn Group currently holds 10.5% of Sharp's shares. The group stated that it will not increase or reduce its holdings at this stage and will maintain its holdings.

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.
