Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - 在不同页面上无法访问socket.emit()函数(socket.emit() function not accessible on different pages)

I have a app.js file Where I initialize my socket code.

(我有一个app.js文件,在其中初始化我的套接字代码。)

app.js

(app.js)

  const io = require('socket.io');
  const server = io.listen(3003);

  const triggerEvent = (socket) => {
    return socket.emit('event-trigger', true);
  }

  server.on('connection', function (socket) {
    console.log('user connected');
    triggerEvent(socket);
  });

This works fine.

(这很好。)

But I am unable to invoke that function on other pages.

(但是我无法在其他页面上调用该函数。)

I exported this function but not work.

(我导出了此功能,但不起作用。)

What I have done is: On Same app.js page

(我所做的是:在同一app.js页面上)

const io = require('socket.io');
  const server = io.listen(3003);

  const triggerEvent = (socket) => {
    return socket.emit('event-trigger', true);
  }

  server.on('connection', function (socket) {
    console.log('user connected');
    triggerEvent(socket);
  });
 module.exports.triggerEvent = (socket) => {
    return socket.emit('event-trigger', true);
  }

and Now on other page, let's say test.js

(现在在另一页上,假设为test.js)

const mySocket = require('./app.js');

//Under  some function, I call this function to invoke the trigger on Frontend,

someOtherTestFunction() {
  ...
  ...
  mySocket.triggerEvent() // but it will not invoke the FE.
}

Can anyone guide me what is the efficient and best way to do this?

(谁能指导我这样做的最有效和最佳方法是什么?)

Any help or suggestion is really appreciated.

(任何帮助或建议都非常感谢。)

  ask by Aks translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...