7-观察者模式

<!DOCTYPE html>
<html lang='en'>

<head>
    <meat charset='UTF-8' />
    <meat name='viewport' content='width=device-width, initial-scale=1.0' />
    <style>

    </style>
</head>

<body>
    <div id="show">

    </div>

    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        /**
         * 实现Event类
         *  需要实现的方法
         *      1.on()方法,接收两个参数,绑定自定义事件名称和事件方法
         *      2.commit(),接收多个参数,触发自定义事件,且传参给事件方法
         *      3.remove(),接收一个参数,删除指定的自定义事件
         *      4.empty(),清空所有自定义事件
         *      5.once(),接收两个参数,绑定自定义事件名称和事件方法,但只触发一次
        */
        function Event() {
            this.cache = {}; // 缓存自定义事件
        }
        Event.prototype.on = function (type, func) {
            if (this.cache[type] === undefined) {
                this.cache[type] = [];
            }
            this.cache[type].push(func)
        }
        Event.prototype.commit = function () {
            let type = arguments[0];
            let args = [].slice.call(arguments, 1);
            if (!this.cache[type]) throw new Error('not find ' + type);
            // 如果是‘once’方法添加的自定义事件就只执行一次
            if (this.cache[type].constructor === Array) {
                this.cache[type].forEach((item) => {
                    item.apply(this, args);
                })
            } else {
                this.cache[type].arrFunc.forEach((item) => {
                    item.apply(this, args);
                })
                this.cache[type].arrFunc = [];
            }
        }
        Event.prototype.empty = function (type) {
            this.cache[type] = [];
        }
        Event.prototype.remove = function (type, func) {
            this.cache[type] = this.cache[type].filter((item) => {
                return item !== func
            })
        }
        Event.prototype.once = function (type, func) {
            if (this.cache[type].construtor === undefined) {
                this.cache[type] = {};
                this.cache[type].arrFunc = [];
                this.cache[type].name = 'once';
            }
            this.cache[type].arrFunc.push(func);
        }

        let event = new Event();
        let del = function (num) {
            console.log('只执行一次---', num * 50);
        }
        event.on('del', del);
        event.on('test', function (num, a, b, c) {
            console.log(num, a, b, c, '----------')
        })
        event.once('del', del);
        event.once('del', del);
        event.once('del', del);
        event.once('del', del);

        event.commit('test', 50, 80, 90, 100);
        event.commit('test', 50, 80, 90, 100);
        event.commit('del', 50, 80, 90, 100);

    </script>
</body>

</html>

你可能感兴趣的:(JS设计模式)