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

作者: immutable | 来源:发表于2016-09-25 11:43 被阅读2396次

前言

学过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 的数字发生改变.

相关文章

  • eventBus源码解析

    EventBus定义:是一个发布 / 订阅的事件总线。 发布者,订阅者,事件,总线。 EventBus,可以说,就...

  • EventBus原理解析

    EventBus(发布订阅事件总线):通过解耦发布者和订阅者简化android 事件传递 EventBus is ...

  • EventBus源码(一)

    1、EventBus概述: EventBus是Android中发布订阅事件总线框架,将事件的发布者和订阅者分开, ...

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

    前言 学过Android的同学应该都用过的一个框架->EventBus. 在我们需要的地方设置一个监听,在另外一段...

  • 初识EventBus

    What 发布/订阅事件总线, EventBus is an open-source library for An...

  • EventBus源码分析

    EventBus EventBus是一个为Android和Java平台设计的发布/订阅事件总线 EventBus有...

  • Android EventBus 的使用

    1、EventBus 简介 EventBus是一种用于Android的事件发布-订阅总线,由GreenRobot开...

  • 实现RxBus代替EventBus

    EventBus是什么 EventBus是为Android优化的发布/订阅事件总线 [图片上传失败...(imag...

  • Android EventBus 的使用

    1、EventBus 简介 EventBus是一种用于Android的事件发布-订阅总线,由GreenRobot开...

  • Android EventBus 源码解析及使用说明

    1、EventBus 简介 EventBus是一种用于Android的事件发布-订阅总线,由GreenRobot开...

网友评论

  • 9e28948dcdf3:rn里面自带的有事件监听方法…
  • 幸福的李雨龙:最近在看着一块,iOS好看懂,Android全是jar,翻阅好麻烦啊
  • 2dab7f8bb652:为什么不用redux?
    immutable:@软件人阿锋 我上面说的情景确实都可以用redux来替代, redux 管理的是state状态机,只能适用于组件View的状态监听. 但也有逻辑是与View无关的,例如: 用户在使用APP的某一时刻,对用户行为的上传.在这里,用户行为上传这种操作就属于与UI无关.

本文标题:react-native 发布/订阅事件总线EventBus 使

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