Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Created November 4, 2015 17:50
Show Gist options
  • Save dhrrgn/eb170f71c77c287c756d to your computer and use it in GitHub Desktop.
Save dhrrgn/eb170f71c77c287c756d to your computer and use it in GitHub Desktop.
/**
* @providesModule KeyboardMixin
*/
'use strict';
import React from 'react-native';
var {
DeviceEventEmitter,
} = React;
/**
* A nice wrapper around KeyboardEvents to make them easier to use.
*
* ### Basic Usage
*
* You must first add the Mixin to the component, then you can define any of the functions define 2 methods:
*
* - `onKeyboardWillShow`
* - `onKeyboardWillShow`
* - `onKeyboardWillHide`
* - `onKeyboardDidHide`
*
* Example:
*
* var Something = React.createClass({
* mixins: [KeyboardMixin],
*
* onKeyboardWillShow(event) {
* // Do something
* },
* onKeyboardWillHide() {
* // Do something
* },
* });
*/
const events = {
keyboardWillShow: 'onKeyboardWillShow',
keyboardDidShow: 'onKeyboardWillShow',
keyboardWillHide: 'onKeyboardWillHide',
keyboardDidHide: 'onKeyboardDidHide',
};
var KeyboardMixin = {
componentDidMount() {
this.keyboardListeners = [];
for (event in events) {
if (events.hasOwnProperty(event) && typeof this[events[event]] === "function") {
this.keyboardListeners.push(DeviceEventEmitter.addListener(event, this[events[event]]));
}
}
},
componentWillUnmount() {
for (let i = 0, len = this.keyboardListeners.length; i < len; i++) {
this.keyboardListeners[i].remove();
}
},
};
module.exports = KeyboardMixin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment