2019年底

// 简易版emit/on
function Pubsub(){
     //存放事件和对应的处理方法
    this .handles = {};
 }
 Pubsub.prototype={
     //传入事件类型type和事件处理handle
     on:   function (type, handle) {
         if (!  this .handles[type]){
             this .handles[type] = [];
         }
         this .handles[type].push(handle);
     },
     emit:   function () {
         //通过传入参数获取事件类型
        var type = Array.prototype.shift.call(arguments);
        console.log(type,   'type' );
         if (!  this .handles[type]){
             return false ;
         }
 for (  var i = 0; i <   this .handles[type].length; i++) {
             var handle =   this .handles[type][i];
             //执行事件
            console.log(handle,   'handle' , arguments);
            handle.apply(  this , arguments);
         }
     },
     off:   function (type, handle) {
         handles =   this .handles[type];
         if (handles){
             if (!handle){
                 handles.length = 0;  //清空数组
            }  else {
 for (  var i = 0; i < handles.length; i++) {
                     var _handle = handles[i];
                     if (_handle === handle){
                         handles.splice(i,1);
                     }
                 }
             }
         }
     }
 }

 var p1 =   new Pubsub();
 p1.on(  'mm' ,   function (name) {
     console.log(  'mm: ' + name);
 });
 p1.emit(  'mm' ,  '哈哈哈哈' );


// 洋葱圈模型
// 实现方式一
function compose (middleware) {
   return async   function () {
      let args = arguments
      await dispatch(0)
      function async dispatch (i) {
         const fn = middleware[i]
         if (!fn)   return null
         await fn(  function next () {
            dispatch(i + 1)
         }, ...args)
      }
   }
}
// 实现方式二
function compose(middlewares=[fn1,fn2,fn3])
{
    function dispatch(i)
    {
        let fn=middlewares[i]
        if (!fn){
            return Promise.resolve()
        }
        else
        {
            return new Promise((resolve)=>{
                resolve(fn(  function next () {
                    return dispatch(i + 1)
                }));
            });
        }
    }
    return dispatch(0);
}

  

 

posted @ 2019-12-23 19:52  Paxster  阅读(226)  评论(0编辑  收藏  举报