美文网首页
javascript观察者模式简述

javascript观察者模式简述

作者: 站着瞌睡 | 来源:发表于2018-10-09 11:38 被阅读0次

    观察者模式又称发布订阅模式publish-subscribe,是存在普遍存在与js和大多数语言的一种消息机制。js的事件机制就是发布订阅模式,从而实现异步。

    In software architecture, publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead categorize published messages into classes without knowledge of which subscribers, if any, there may be.

    简单的实现如下

    const _ = window._ //lodash
    let Event = (function () {
      let p = {}
      let usid = -1
      let topics = {}
      p.publish = function (topic, args) {//发布
        if (!topics[topic]) { return }
        let sub = topics[topic]
        for (let i = 0; i < sub.length; i++) {
          sub[i].func(args, topic)
        }
        return this
      }
      p.subscribe = function (topic, func) {//订阅
        topics[topic] = topics[topic] || []
        let token = ++usid
        let sub = topics[topic]
        sub.push({
          token,
          func
        })
        return token
      }
      p.unsubscribe = function (topic, token) {//取消订阅
        if (!topics[topic]) { return }
        let sub = topics[topic]
        _.remove(sub, (n) => n.token === token)
        if (sub.length === 0) {
          delete topics[topic]
        }
        return this
      }
      return p
    })()
    
    export default Event
    
    

    相关文章

      网友评论

          本文标题:javascript观察者模式简述

          本文链接:https://www.haomeiwen.com/subject/mwtmoftx.html