Home Web Front-end JS Tutorial Singleton package addition, deletion, modification and check

Singleton package addition, deletion, modification and check

Mar 23, 2018 pm 03:48 PM
encapsulation

This time I will bring you the Singleton encapsulation of addition, deletion, modification and check. What are the precautions for the Singleton encapsulation of addition, deletion, modification and check? The following is a practical case, let’s take a look.

The example of this article describes how JS implements the function of encapsulating the addition, deletion, modification and checking of data based on the singleton mode (Singleton) in the design pattern. 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 is instantiated and provided 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();
Copy after login
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("新增出现异步,请得新增加或联系技术管理员");
  }
  });
});
Copy after login
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("新增出现异步,请得新增加或联系技术管理员");
  }
  });
});
Copy after login
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 );
});
Copy after login
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;
   }
  }
 }
})();
Copy after login
The ajax method in SingleClass is also equivalent to a facade mode (Facade), hiding internal details and exposing an interface to the outside;

I believe you have read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the scope and pre-parsing of js

Dynamic display of select drop-down list data

The above is the detailed content of Singleton package addition, deletion, modification and check. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

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

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

Packaging technology and application in PHP Packaging technology and application in PHP Oct 12, 2023 pm 01:43 PM

Encapsulation technology and application encapsulation in PHP is an important concept in object-oriented programming. It refers to encapsulating data and operations on data together in order to provide a unified access interface to external programs. In PHP, encapsulation can be achieved through access control modifiers and class definitions. This article will introduce encapsulation technology in PHP and its application scenarios, and provide some specific code examples. 1. Encapsulated access control modifiers In PHP, encapsulation is mainly achieved through access control modifiers. PHP provides three access control modifiers,

Introduction to Axios encapsulation and common methods in Vue Introduction to Axios encapsulation and common methods in Vue Jun 09, 2023 pm 04:13 PM

Introduction to Axios encapsulation and common methods in Vue Axios is an HTTP library based on Promise. Its advantage is that it has good readability, ease of use and scalability. As a popular front-end framework, Vue also provides full support for Axios. This article will introduce how to encapsulate Axios in Vue, and introduce some commonly used methods of Axios. 1. Axios encapsulation During the development process, we often need to perform some customized encapsulation of Axios, such as

Foxconn builds AI one-stop service, and invested Sharp to enter advanced semiconductor packaging: put into production in 2026, designed to produce 20,000 wafers per month Foxconn builds AI one-stop service, and invested Sharp to enter advanced semiconductor packaging: put into production in 2026, designed to produce 20,000 wafers per month Jul 18, 2024 pm 02:17 PM

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.

How to resolve poor scalability error in Python code? How to resolve poor scalability error in Python code? Jun 25, 2023 am 09:51 AM

As a high-level programming language, Python is widely used in data analysis, machine learning, web development and other fields. However, as the size of the code continues to expand, the scalability problem of Python programs gradually becomes apparent. Poor scalability error means that the Python program cannot adapt well to changes in requirements under certain circumstances and cannot process large-scale data, resulting in poor program performance. Too many dependencies, poor code structure, lack of documentation, etc. are all culprits of poor scalability errors in Python programs.

How to implement encapsulation and inheritance in Go language How to implement encapsulation and inheritance in Go language Jul 23, 2023 pm 08:17 PM

How to implement encapsulation and inheritance in Go language Encapsulation and inheritance are two important concepts in object-oriented programming. They can make the code more modular and maintainable, and also provide convenience for code reuse. This article will introduce how to implement encapsulation and inheritance in Go language and provide corresponding code examples. Encapsulation Encapsulation is to encapsulate data and functions, hide implementation details, and only expose necessary interfaces for external use. In Go language, encapsulation is achieved through exported and non-exported identifiers. Identifiers with capital letters can be accessed by other packages

See all articles