From ce116177436a3295d149dfda363613dee1e50ef2 Mon Sep 17 00:00:00 2001 From: plougsgaard Date: Thu, 15 Sep 2016 01:02:26 +0200 Subject: [PATCH] Add event emitter for android. --- index.js | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 220dfc1..51ac504 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,7 @@ import React, { Component, PropTypes } from 'react'; import { - NativeAppEventEmitter, + DeviceEventEmitter, // android + NativeAppEventEmitter, // ios NativeModules, Platform, StyleSheet, @@ -144,9 +145,9 @@ export default class Camera extends Component { } async componentWillMount() { - this.cameraBarCodeReadListener = NativeAppEventEmitter.addListener('CameraBarCodeRead', this._onBarCodeRead); + this._addOnBarCodeReadListener() - let { captureMode } = convertNativeProps({captureMode: this.props.captureMode}) + let { captureMode } = convertNativeProps({ captureMode: this.props.captureMode }) let hasVideoAndAudio = this.props.captureAudio && captureMode === Camera.constants.CaptureMode.video let check = hasVideoAndAudio ? Camera.checkDeviceAuthorizationStatus : Camera.checkVideoAuthorizationStatus; @@ -157,13 +158,37 @@ export default class Camera extends Component { } componentWillUnmount() { - this.cameraBarCodeReadListener.remove(); + this._removeOnBarCodeReadListener() if (this.state.isRecording) { this.stopCapture(); } } + componentWillReceiveProps(newProps) { + const { onBarCodeRead } = this.props + if (onBarCodeRead && !newProps.onBarCodeRead) { + this._addOnBarCodeReadListener(newProps) + } + } + + _addOnBarCodeReadListener(props) { + const { onBarCodeRead } = props || this.props + this._removeOnBarCodeReadListener() + if (onBarCodeRead) { + this.cameraBarCodeReadListener = Platform.select({ + ios: NativeAppEventEmitter.addListener('CameraBarCodeRead', this._onBarCodeRead), + android: DeviceEventEmitter.addListener('CameraBarCodeReadAndroid', this._onBarCodeRead) + }) + } + } + _removeOnBarCodeReadListener() { + const listener = this.cameraBarCodeReadListener + if (listener) { + listener.remove() + } + } + render() { const style = [styles.base, this.props.style]; const nativeProps = convertNativeProps(this.props); @@ -172,7 +197,9 @@ export default class Camera extends Component { } _onBarCodeRead = (data) => { - if (this.props.onBarCodeRead) this.props.onBarCodeRead(data) + if (this.props.onBarCodeRead) { + this.props.onBarCodeRead(data) + } }; capture(options) {