我在凤凰城有以下文件夹结构:
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
内,则连接成功,但我希望将它们分开。
答案 0 :(得分:2)
connectToChannel
函数是其定义的文件的本地函数。api.js
和script.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);
});
}