美文网首页
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观察者模式简述

    观察者模式又称发布订阅模式publish-subscribe,是存在普遍存在与js和大多数语言的一种消息机制。js...

  • 设计模式 - 观察者模式

    观察者模式的定义 观察者模式简述 MVC是由各种复杂的设计模式组合而成的复合结构,观察者是其中的设计模式之一。视图...

  • Java设计模式之观察者模式

    简述 观察者模式又称为发布订阅模式,是对象的行为模式。观察者模式定义了一种一对多的依赖关系,多个观察者共同订阅着一...

  • 关于观察者, 发布订阅,中介者的一些学习体会2019-07-05

    w3cSchool javascript 观察者模式w3cSchool javascript 中介者模式 1. 顺...

  • iOS KVO使用

    简述 KVO是key-value-observe的简称,也就是键值观察者,是一种设计模式 -- 观察者模式。核心思...

  • 观察者模式二

    简述 有对观察者模式不清楚的朋友请先查看 观察者模式一 本文利用观察者模式设计一个乘客收到火车到站通知上车和下车...

  • NSNotification&NSNotificatio

    简述 在iOS中,NSNotification & NSNotificationCenter是使用观察者模式来实现...

  • iOS之自定义通知中心(学习的是思想)

    简述在iOS中,NSNotification & NSNotificationCenter是使用观察者模式来实现的...

  • javascript观察者模式

    javascript观察者模式学习笔记 原文地址 首先是观察者模式代码 在观察着模式的运用当中。react组件间的...

  • 观察者模式js实现

    参看书籍JavaScript模式第七章设计模式我的理解:观察者模式又叫订阅/发布模式。被观察者(发布者)内部需要有...

网友评论

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

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