LoginSignup
18

More than 5 years have passed since last update.

フロントエンドで ActionCable を npm 経由で使う

Last updated at Posted at 2016-08-11

近年、我々がRails5をセットアップする際に最初にやることは sprockets を 無効化することだが、 rails5 の Channel は Sprockets ありきで書かれていたので、npm で完結して使えるか調べて、書きなおした。

actioncable を使う。

npm install -S actioncable

どこ由来か怪しくて調べたけど、一応railsのリポジトリから publish されてる?
https://github.com/rails/rails/blob/master/actioncable/package.json

npm に publish した eleencodes は https://github.com/eileencodes 見る限り rails コミッタなので、とりあえず信用できそう。同名の id を npm で騙ってないかぎり。

http://qiita.com/jwako/items/96c01183c9c33ba1a48d を参考に babel/browserify 環境用に書き直す。

import ActionCable from "actioncable";
const cable = ActionCable.createConsumer();
const room = cable.subscriptions.create("RoomChannel", {
  connected() {
    console.log("connected");
  },

  disconnected() {
    console.log("disconnected");
  },

  received(data) {
    console.log("received",  data);
  },

  speak(mes = "hello") {
    this.perform('speak', {mes});
  }
});
export default room;

だいたいこんな感じ

注意点

今はリリース直後だからブレ用がないけど、念のため Gemfile の方とバージョンを固定して合わせておかないと、非互換な変更あったときに死にそう。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18