react-native 发布/订阅事件总线EventBus 使用

721 查看

前言

学过Android的同学应该都用过的一个框架->EventBus. 在我们需要的地方设置一个监听,在另外一段代码中,我们只要发送一个Event,则监听中的代码就会立即执行. 能很大程度上解耦代码.

我们都知道 react-native 是依赖于Node.js的,而在node.js 中,刚好有一个与EventBus 类似的机制 Events.

使用场景

在讲如何使用之前,我们先来看一下,Event 对我们有什么帮助,我们为什么需要使用它.

场景一


该页面显示的内容都是用户所订阅的主播,然后旁边与一个"已订阅"按钮,如果点击,则按钮变成"订阅",注意 头部 "我的订阅( counter )" 这里面的数字是会变动的.

常规处理可能是这样的,该页面肯定是包含多个 组件Component 组成,但 组件Component之间又没有直接关联,所以 我们只能用回调处理,一层层将事件发送到 顶级组件中,然后又分发出去.

使用 Events 后就简单多了,我们可以在头部Component 中注册监听,然后在 ListView的Item中发送Event事件即可实现需求.

场景二

用户登录前后页面状态的更改.

安装使用

安装

将命令行移动到项目的根目录,执行以下: npm install events --save

使用示例

  1. 新建CountEmitter.js 文件
'use strict';

const EventEmitter = require('events');

class CountEmitter extends EventEmitter{

}
const SingleCountEmitter = new CountEmitter();
export default SingleCountEmitter;
  1. 新建 TopPage.js 文件
'use strict';
import React from 'react';
import {
    View,
    Text
} from 'react-native';

import CounterEmitter from './CountEmitter';

class TopPage extends React.Component{

    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            count:0
        };
      }

    componentWillMount() {
        CounterEmitter.addListener('addCounter',()=>{
            let newCount=this.state.count+1;
            this.setState({
                count:newCount
            });
        });
        CounterEmitter.addListener('reduceCounter',()=>{
            let newCount=this.state.count-1;
            this.setState({
                count:newCount
            });
        });
    }

    render(){
        return (
            <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                <Text>Count: {this.state.count}</Text>
            </View>
        );
    }
}

export default TopPage;
  1. 新建BottomPage.js 文件
'use strict';
import React from 'react';
import {
    View,
    Text,
    TouchableOpacity
} from 'react-native';

import CounterEmitter from './CountEmitter';

class BottomPage extends React.Component{

    render(){
        return (
            <View style={{flex:1}}>
              <TouchableOpacity
                  onPress={()=>{
                  CounterEmitter.emit('addCounter');
              }}>
                  <View style={{width:100,height:100,borderRadius:10,backgroundColor:'red',justifyContent:'center',alignItems:'center'}}>
                      <Text style={{color:'white',fontSize:18}}>Add</Text>
                  </View>
              </TouchableOpacity>

              <TouchableOpacity
                  style={{marginTop:40}}
                    onPress={()=>{
                        CounterEmitter.emit('reduceCounter');
                    }}>
                    <View style={{width:100,height:100,borderRadius:10,backgroundColor:'green',justifyContent:'center',alignItems:'center'}}>
                        <Text style={{color:'white',fontSize:18}}>Reduce</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
}

export default BottomPage;
  1. 修改index.android.js
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  View
} from 'react-native';

import TopPage from './TopPage';
import BottomPage from './BottomPage';


class AwesomeProject extends Component {

  render() {
    return (
      <View style={styles.container}>
        <TopPage/>
        <View style={{height:1,backgroundColor:'gray',width:500,marginBottom:50}} />
        <BottomPage/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

最终效果


效果: 在BottomPage 中点击 Add或Reduce 按钮能使 TopPage 的数字发生改变.