0.0.1 • Published 7 years ago

umineko-nerv v0.0.1

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

js-csp(一种 CSP 模型的 JS 实现库)为基础,实现 React Component 间新的通信模式。

此通信库主要有两部分组成:

  • 大脑 Brain:主要承担接受外部信息和处理内部数据的任务。
  • 神经节点 NervNode:整个神经树上的一个节点,能够向神经树发送数据,也能从神经树中读取数据。

将神经节点(NervNode)注入到想其他组件进行数据通信的 Component 上,神经节点就会依赖 Component 树建立起一颗 NervTree。

API

下面使用 flow 的方式来声明 API。

insertNerv

inertNerv 用法与 Redux 的 connect 类似。

// 监听 NervNode 中 message 的函数,Message 类型见下
declare function listenMessageFunc(
  msg: Message, 
  props: Object
): Object 

// 内部 Dispatch 函数 
declare function NervDispatchFunc(msg: Message): void

declare function dispatchFunc(dispatch: NervDispatchFunc): { [any]: function }

declare function insertNerv(
  listenMessage: listenMessageFunc, 
  dispatchObject: { 
    up: dispatchFunc, 
    down: dispatchFunc 
  }
): void

样例

import React from 'react'
import { insertNerv, message } from 'umineko-nerv'

class TestComponent extends React.PureComponent {
  constructor(props) {
    super(props)
    this.times = 0
  }

  render() {
    return(
      <div onClick={() => {this.props.triggerTimes(this.times++)}} >
        { this.props.test }
      </div>
    )
  }
}

const listenMessage = (action) => {
  if (action.isMatch('hi.hello')) {
    return { test: action.preload.info }
  }
}

const mapUpDispatchToProps = (dispatch) => {
  return {
    triggerTimes: (times) => { message.data('test.times', { times: times }) }
  }
}

export const TestComponentNerv = insertNerv(listenMessage, { up: mapUpDispatchToProps })(TestComponentNerv)

Brain

Brain 与其 Provider 类似。

declare function loop(msg: Message): Message
declare function receptor(dispatch: NervDispatchFunc): void 

样例

<Brain loop={brainLoop} receptor={receptor}>
  <YourAppRoot />
</Brain>

Message

Message 是 NervTree 中基本数据单元类,也即是说在 NervTree 中传递的数据要使用 Message 来封装。

interface Message {
  type: string,
  prior: number,
  topic: string,
  data: Object,
  isMatch(pattern: string): boolean
  isEmpty(): boolean
  toString(): string
}

同时提供5个基础类型的 message 工厂函数以供使用

empty(): Message
data(topic: string, data: Object): Message
animation(topic: string, data: Object): Message
route(topic: string, params: Object): Message
sign(topic: string, data: Object): Message