Simulation and variable parameters of js publish and subscribe model

1, Application

  1. Widely used in asynchronous programming, it is an alternative to callback function. Subscribe to an event. The event occurs after operation A (listening to operation A)
  2. Instead of the hard coded notification mechanism between objects, one object does not need to call another object's interface to make the two objects loosely coupled. Although the details of each other are not clear, they do not affect the communication between them.

1. Dom event

A typical publishing subscriber mode. An event ('click, mousedown, etc ') listens to a dom node, operates the dom node, triggers the event, and executes the response function. The event function is completely unknown to the dom node. It's good to publish without paying attention to the content of the event function.

2. User defined events

  • Specify publisher
  • Give the publisher a cache list. An object consists of n key value pairs. The key represents the event name. The value is an array of event handlers, which is equivalent to the subscriber roster
  • Publish the message, traverse the cache list, and execute the callback function of the subscriber in turn.

 

Simple publish and subscribe model and variable parameters

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>

</body>
<script type="text/javascript">
    // The passing of array variable parameters
    // ... as a remainder operator in the parameter list, as an expansion operator in the parameter pass
    function f1(a, ...args) {
        console.log(args, typeof(args)) //2 3 4 5 Object
        f2(args) // 2 3 4 5 undefinded undefinded
        f2(...args) //2 3 4
    }

    function f2(a, b, c) {
        console.log(a, b, c)
    }

    f1(1, 2, 3, 4, 5)

    function Gril() {
        this._events = {}

        this.on = (eventName, callback) => {
            console.log('on');
            if (this._events[eventName]) {
                this._events[eventName].push(callback)
            } else {
                this._events[eventName] = [callback]
            }
        }
        this.emit = (eventName) => {
            console.log('emit');
            if (this._events[eventName]) {
                this._events[eventName].forEach(item => item())
            }
        }
    }

    let cry = () => {
        console.log('cry');
    }
    let eat = () => {
        console.log('eat');

    }
    let g = new Gril()
    g.on('Lovelorn', cry)
    g.on('Lovelorn', eat)
    g.emit('Lovelorn')

    let gg = new Gril()
    gg.emit()
    gg.on('happy', eat)
    gg.emit('happy')
</script>

</html>

Tags: Programming Javascript

Posted on Mon, 04 May 2020 20:12:49 -0400 by superdezign