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

时间:2016-03-23 22:51:41

标签: jquery function sockets phoenix-framework brunch

我在凤凰城有以下文件夹结构:

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时,我在浏览器的控制台中收到以下错误:

  

未捕获的ReferenceError:未定义connectToChannel

如果我使用socket.js的内容并将其放在script.js内,则连接成功,但我希望将它们分开。

1 个答案:

答案 0 :(得分:2)

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);
  });
}