Last active
June 22, 2018 17:43
-
-
Save reggie3/4cb9caad0a7361f064ec59a21faa5a3a to your computer and use it in GitHub Desktop.
webview parent component handle message gist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
handleMessage = (event) => { | |
let msgData; | |
try { | |
msgData = JSON.parse(event.nativeEvent.data); | |
if ( | |
msgData.hasOwnProperty('prefix') && | |
msgData.prefix === MESSAGE_PREFIX | |
) { | |
console.log(`WebViewLeaflet: received message: `, msgData.payload); | |
// If a message object includes an 'event' key then the webpage is sending an event, | |
// Pass it to the parent by calling the parent function that has the same name | |
// as the event, and passing the entire payload as the argument to that event | |
if ( | |
// check to see if an event key exists | |
msgData.payload.event && | |
// check to see if the eventReceiver (typically the parent component) has a matching | |
// function for this event | |
this.props.eventReceiver.hasOwnProperty(msgData.payload.event) | |
) { | |
// call the function, and pass it the payload as the argument | |
this.props.eventReceiver[msgData.payload.event](msgData.payload); | |
} | |
// If no event key was found, then update the eventReceiver's state | |
else { | |
this.props.eventReceiver.setState({ | |
state: { | |
...this.props.eventReceiver.state, | |
mapState: { | |
...this.props.eventReceiver.mapState, | |
...msgData.payload | |
} | |
} | |
}); | |
} | |
} | |
} catch (err) { | |
console.warn(err); | |
return; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment