Created
May 10, 2019 14:22
-
-
Save mattsan/aa6b0dc7e603bc676caeb35186b077f3 to your computer and use it in GitHub Desktop.
Action Cable + Stimulus
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
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) |
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
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 |
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
import { createConsumer } from '@rails/actioncable' | |
const consumer = createConsumer() | |
export default consumer |
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
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