首页 > 解决方案 > How require only a channel that I need?

问题描述

All channels are created on folder javascript/channels and by default, all inner this path is loaded.

To not require all I just delete the file channels/index that contains:

// Load all the channels within this directory and all subdirectories.
// Channel files must be named *_channel.js.

const channels = require.context('.', true, /_channel\.js$/)
channels.keys().forEach(channels)

But how require my channels at pages that I need?

Using = javascript_pack_tag "channels/my_channel" at pages that I need doest work.

Which are is the best practices? How keep many channels and require only where I need?

标签: ruby-on-railsactioncable

解决方案


频道 js 文件(确切地说是频道订阅者)通常包含类似

const channel_subscription = consumer.subscriptions.create({
  channel: 'SomeChannel',
  received: function(data) {...}
});

订阅在执行时创建(默认在页面加载时),但您可以将其设为函数:

function connect_this_exact_channel() {
  return consumer.subscriptions.create(...)
}

并且仅在调用该函数时才会创建订阅。


推荐阅读