Last active
January 3, 2016 16:49
-
-
Save julik/8492257 to your computer and use it in GitHub Desktop.
Add leaf-to-branch signaling to React
This file contains 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
# A module that allows us to send Backbone events up the tree of components | |
ReactTelegraph = | |
componentWillMount: -> | |
# Make BB events available to the component | |
_.extend @, Backbone.Events | |
componentWillUnmount: -> | |
# Remove all Backbone event listeners | |
@off null, null, null | |
# Shortcut for triggerWithBubbling | |
upstream: (ar...)-> | |
@triggerWithBubbling(ar...) | |
triggerWithBubbling: (ar...)-> | |
# Trigger the event on myself using partial application | |
@trigger.bind(@, ar...)() | |
# And telegraph the event up the component tree | |
parent = @props.__owner__ | |
# Only do this if the owner component responds to "triggerWithBubbling" | |
# - the extension indicates that the component participates in the | |
# Telegraph system and has the mixin | |
if parent and parent.triggerWithBubbling | |
parent.triggerWithBubbling(ar...) | |
# Return self | |
@ | |
window.ReactTelegraph = ReactTelegraph | |
MyButton = React.createClass | |
mixins: [ReactTelegraph] | |
upvoteClicked: -> | |
@triggerWithBubbling 'upvote', @props.commentId | |
render: -> | |
(button {onClick: @upvoteClicked}, "Upvote comment #{@props.commentId}!") | |
MyComponent = React.createClass | |
mixins: [ReactTelegraph] | |
render: -> | |
(div {}, (MyButton {commentId: 123}), (MyButton {commentId: 234})) | |
componentDidMount: -> | |
# Listen to the "upvote" | |
# event via BB events, it's going to be | |
# sent from one of the children | |
@on 'upvote', (cid) -> | |
# Do whatever we have to do | |
console.debug "Comment #{cid} upvoted" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment