Web Front-end
JS Tutorial
Singleton mode in JS implements addition, deletion, modification and query of dataSingleton 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!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools





