Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

写一个观察者模式(发布-订阅模式)例子 #1

Open
twosugar opened this issue Mar 28, 2019 · 0 comments
Open

写一个观察者模式(发布-订阅模式)例子 #1

twosugar opened this issue Mar 28, 2019 · 0 comments

Comments

@twosugar
Copy link
Owner

twosugar commented Mar 28, 2019

当一个对象的状态发生改变时,所有依赖与它的对象都将得到通知,在实际开发中,若多个事件共同依赖同一条件,那么可以将这些事件放入一个数组之中。在我看来,这样做更加清晰规范,便于项目的维护。下面手写一个简单的例子:

const eventsWacth = (function(){
  var events = {} //定义一个存储事件的对象

  function on(name, action) { //name: 事件名称; action: 对应执行函数
    events[name]= events[name] || []
    events[name].push({ //将执行函数push进数组列表
      action
    });
  }

  function emit(name,  args) {// args: 参数
    if (!events[name]) { //未找到 return
      return
    }
    for(let i = 0; i < events[name].length; i ++) { //事件名称有可能对应多个函数
      if(events[name][i] && events[name][i].action) { //如在事件数组中找到对应函数 执行
        events[name][i].action(args)
      }
    }
  }

  function off(name){ //销毁
    delete events[name];
}

  return {
    on,
    emit,
    off
  }

})()


var f1 = function(val) {console.log(1111 + val)}
var f2 = function(val) {console.log(2222 + val)}

eventsWacth.on('first', f1)
eventsWacth.emit('first', 'tyty') //1111tyty
eventsWacth.on('first', f2)
eventsWacth.emit('first', 'tyty')// 打印1111tyty和2222tyty
eventsWacth.on('second', f1)
eventsWacth.emit('second', 'hello world!') // 1111hello world!

每天学习一点点

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant