1.0.3 • Published 7 years ago

preact-suber v1.0.3

Weekly downloads
6
License
MIT
Repository
github
Last release
7 years ago

Binding function withBus between Preact and Suber.

Usage

Install:

yarn add preact-suber
# or
npm install preact-suber --save

Usage:

import preact from 'preact'
import { createBus } from 'suber'
import { withBus, BusProvider } from 'preact-suber'

// Create a component that will listen on the 'SHOW_WARNING' channel
// It expects 'bus' as a prop
class WarningBanner extends preact.Component {
  constructor () {
    super()
    this.state = {
      warning: null
    }
  }
  componentDidMount() {
    // Start listening for events on component mount
    // When something arrives, set component state to the warning message
    this.stop = this.props.bus.take('SHOW_WARNING', (msg) => {
      this.setState({ warning: msg.warning })
    })
  }
  componentWillUnmount() {
    // Stop listening on unmount
    this.stop()
  }
  render () {
    // Show the warning (if present)
    if (!this.state.warning) return null
    return <blink>{ this.state.warning }</blink>
  }
}

// Create a component will can send on the 'SHOW_WARNING' channel
// when clicked. It expects 'bus' as a prop
const SenderButton = ({ bus, children }) => {
  const onClick = () => bus.send('SHOW_WARNING', { warning: 'Hacking detected!' })
  return <button onClick={ onClick }>{ children }</button>
}

// To automatically pass the bus to these components
// we wrap them with 'withBus'
const WarningBannerWithBus = withBus(WarningBanner)
const SenderButtonWithBus = withBus(SenderButton)

// We use these wrapped components just as we
// would with the original components
// Remember to wrap your app in BusProvider to make the bus available
// for all components
const bus = createBus()
preact.render(
  <BusProvider bus={bus}>
    <WarningBannerWithBus />
    <SenderButtonWithBus>Click me!!!</SenderButtonWithBus>
  </BusProvider>
  , document.getElementById('app')
)

API

Components

Functions

BusProvider

Provider component that makes the bus available for withBus through the context.

Attributes

  • bus: Object A Suber bus. Import and invoke createBus() from Suber to create one.

withBus(component)

Returns the wrapped component with the bus prop injected.

Arguments

  • component: Component Preact component. Can be PureComponent or regular Component

Returns a new React Component

Development setup

yarn
npm run dev
1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

0.1.0

7 years ago