从另一个 js 文件调用通道连接功能

Call channel connect function from another js file

我在 phoenix 中有以下文件夹结构:

web/
  static/
    js/
      app.js
      script.js
      socket.js

app.js 有...

import socket from "./socket"

import script from "./script"

brunch-config.js 有...

files: {
    javascripts: {
      joinTo: "js/app.js"
    }
    // ...
}

script.js 有...

$('#some-button').on('click', function() {
    connectToChannel(data);
});

socket.js 有...

import {Socket} from "phoenix"

let socket = new Socket("ws://example.com/updates", {params: {"auth-token": "AUTH-TOKEN"}})

function connectToChannel(data) {
    socket.connect()

    let channel = socket.channel("updates:new", {})
    channel.join()
      .receive("ok", resp => { console.log("Joined successfully", resp) })
      .receive("error", resp => { console.log("Unable to join", resp) })

    channel.on("update", payload => {
        console.log(payload);
    })
}

export default socket

...但是当我单击 some-button 时,我在浏览器的控制台中收到以下错误:

Uncaught ReferenceError: connectToChannel is not defined

如果我把socket.js的内容放到script.js里面就连接成功了,但是我想把它们分开。

connectToChannel 函数在其定义的文件中是本地的。api.jsscript.js 都看不到它。

你可以做的是从 socket.js 导出它并传递给 app.js,像这样:

// socket.js

import {Socket} from "phoenix"

let socket = new Socket("ws://example.com/updates", {params: {"auth-token": "AUTH-TOKEN"}})

function connectToChannel(data) {
    socket.connect()

    let channel = socket.channel("updates:new", {})
    channel.join()
      .receive("ok", resp => { console.log("Joined successfully", resp) })
      .receive("error", resp => { console.log("Unable to join", resp) })

    channel.on("update", payload => {
        console.log(payload);
    })
}
// export the function too
export {socket, connectToChannel}


// app.js
import {socket, connectToChannel} from "./socket"

import script from "./script"

// pass the fn explicitly
script(connectToChannel);

最后将 script.js 包装在接收 connectToChannel:

的函数中
export default function(connectToChannel) {
  $('#some-button').on('click', function() {
    connectToChannel(data);
  });
}