Skip to content

Instantly share code, notes, and snippets.

@mattsan
Created May 10, 2019 14:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattsan/aa6b0dc7e603bc676caeb35186b077f3 to your computer and use it in GitHub Desktop.
Save mattsan/aa6b0dc7e603bc676caeb35186b077f3 to your computer and use it in GitHub Desktop.
Action Cable + Stimulus
require('@rails/ujs').start()
require('turbolinks').start()
import { Controller, Application } from 'stimulus'
import HomeChannel from './home_channel'
class HomeController extends Controller {
static targets = [
'message'
]
initialize() {
this.channel = new HomeChannel(this)
}
get message() {
return this.messageTarget.textContent
}
set message(msg) {
this.messageTarget.textContent = msg
}
append() {
this.channel.append(this.message + '+')
}
appended(data) {
this.message = data
}
}
const application = Application.start()
application.register('home', HomeController)
import consumer from './consumer'
class Channel {
constructor(channel, options = {}) {
this.subscription = consumer.subscriptions.create(
{ channel, ...options },
{ received: (data) => this.received(data) }
)
}
// data = {action: 'action_name', paylpad: 'payload of some data'}
received(data) {
if (this[data.action]) {
this[data.action](data.payload)
}
}
}
export default Channel
import { createConsumer } from '@rails/actioncable'
const consumer = createConsumer()
export default consumer
import Channel from './channel'
class MyChannel extends Channel {
constructor(listener, options = {}) {
super('MyChannel', options)
this.listener = listener
}
// outgoing function
append(text) {
this.subscription.perform('append', { payload: text })
}
// incomming function
appended(payload) {
this.listener.appended(payload)
}
}
export default HomeChannel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment