Introduction to JavaScript design patterns and practices in the framework

Source: Internet
Author: User
Tags es6 class
In the process of writing JS and assembling code, using a certain design pattern can make our code more elegant and flexible. In the process of writing JS and assembling code, using a certain design pattern can make our code more elegant and flexible.

The following is a brief introduction of the design pattern in these libraries, syntaxes and frameworks by combining the $ dispatch in the vue, ES6 class, redux subsscribe, and jquery on/off..

Problems solved by the design model

The design pattern is not very mysterious. Many developers have inadvertently used many design patterns when writing JavaScript code.

The author believes that the design pattern is abstracted separately to describe a common JS pattern, just like the bubble and sort in the algorithm.

By studying this pattern, let the pattern guide our code structure and JS algorithm.

Some common design patterns

Observer [observer mode]

Actively triggers callback behavior of the observer queue and hashMap based on status changes

A simple observer mode code practice

Class StateTracker {constructor () {this. observers = []; this. internamState = 10;} // Changes the internal status. The observer list that triggers the status change (val) {this. internamState = val; this. observers. forEach (observer => observer (val);} registerObserver (ObserverFn) {this. obserers. push (ObserverFn )}}

Publish/subscribe [subscription and publishing mode]

The topic/callback format of hashMap is stored in the shared access space of the Code module.

Add on/off/trigger and Other interfaces for mounting, removing, triggering, and other actions.

Code practices for a simple subscription and publishing Mode

Class PubSubHandler {constructor () {this. eventPool = {};}// remove off (topicName) {delete this. observers [topicName]} // trigger (topicName ,... args) {this. eventPool [topicName] & this. eventPool [topicName]. forEach (callback => callback (... args);} // subscribe to on (topicName, callback) {let topic = this. eventPool [topicName]; if (! Topic) {this. eventPool [topicName] = []} this. eventPool [topicName]. push (callback )}}

Singleton [singleton mode]

There is only one constructor instance. Generally, internal instances are stored through closures and accessed through interfaces.

var singleton = ()=>{    var instance;    var createInstance = ()=>{        this.a = 1;        this.b = 2;    }    return {         getInstance:()=>{            if(!instance){               instance = createInstance();           }            return instance;         }     }}var test = singleton();test.getInstance() == test.getInstance() //true

Decorator hybrid mode

In this mode, more actions are decorated on the original object and the variable name remains unchanged. If you have used ES7 @ decorator or python, you should be familiar with decorator.

Function decorator (sourceObj, decortorFn) {decortorFn (sourceObj); return sourceObj} var d = {a: 1}; // d to {a: 1, B: 1} d = decorator (d, (d) => {d. B = 1 });

Mixin Mixed Mode

This mode is similar to decorator, but its function is more vertical. It is the behavior of adding and overwriting objects on the original object. Compared with methods such as extends and Object. assign, The mixin mode is more expressive. The mixin mode cannot be generalized, and there may be different mixin policies based on different data types, such as vue. mixin

class StateTracker{   constructor(){       this.raw = {           a:1,            b:2         }     }   mixin(obj){        Object.assign(this.raw,obj)   }}

I will introduce so many design patterns for the time being. The following describes the application of these design patterns for common frameworks, syntaxes, libraries, and so on.

Use of observer mode in redux

Var store = createStore (CER, initialState); // register the redux store and store it in the nextListeners array var test = store. subscribe () => {console. log ('I registered! ')}); // Cancel registration listening test. unsubscribe (); Use of publish/subscribe in jquery $ (document ). on ('hello', () => {console. log ('hello')}) $ (document ). trigger ('hello'); $ (document ). off ('hello ')

Decorator mode practices in react-redux

// Modifier @ connect (state => state) class Container extends Component {render () {return JSON. stringify (this. props )}}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.