如何在用户离开 Meteor and/or Iron router 中的页面时捕获?

How to catch when a user leaves the page in Meteor and/or Iron router?

我正在尝试捕捉 用户何时从我的 Meteor 应用程序(版本 1.2.0.2)离开;相当于服务器端的SocketIO disconnect()

用户可以关闭他的浏览器,转到另一个网站或简单地刷新页面它仍然会触发

令人惊讶的是,我在 Internet 上搜索时发现一切都乱七八糟,无法正常工作。我认为 Meteor 确实是基于这种神奇的实时处理,因此它必须以某种方式管理此事件。

Iron router 文档指定了这个:

onStop: Called when the route is stopped, typically right before a new route is run.

我还发现了 Router.loadRouter.unload,但其中 none 有效。这是我当前的[不工作]代码,非常简单

Router.configure
  layoutTemplate: 'MasterLayout'
  loadingTemplate: 'Loading'
  notFoundTemplate: 'NotFound'

Router.onStop (->

  console.log('Try to stop')
  Users.insert({

    name: "This is a test"
    lat: 0
    lng: 0

    })

)

我是不是做错了什么?你如何在我的应用程序中捕获此事件?

您需要附加到路由的 onStop,而不是路由器。例如:

Router.route('/', {
    onStop: function() {
        console.log("someone left the '/' route");
    }
});

另一种选择是使用onStop event of subscriptions. That is probably the option most similar to the socketio disconnect you mentioned. You can find an example of that in the typhone source code

有两个解决方案,我在 API Documentation 中搜索了一会儿,找到了第二个也是最好的一个。

第一个解决方案:使用订阅和发布

在控制器/前端的任何地方你都必须订阅一个集合

# in coffee
@subscribe('allTargets')

# in javascript
this.subscribe('allTargets')

之后您只需发布并添加一个 onStop 侦听器。这个例子将采用我之前在某处定义的 Targets 集合,它只获取所有条目。

# in coffee
Meteor.publish 'allTargets', ->

  @onStop ->

    # Do your stuff here

  return Targets.find()

# in javascript
Meteor.publish('allTargets', function() {

  this.onStop(function() {

      // Do your stuff here

  });

  return Targets.find();

});

在设置 onStop 侦听器之前,请注意不要 return Targets.find()。我认为这不是一个完美的解决方案,因为您不监听连接本身,而是监听集合的变化。

第二种解决方案:使用 DDP 连接

我通过Meteor实现了API Documentation我们可以直接监听连接,看看是否有人从服务器端断开连接。

为了在我的 Meteor Iron 项目中保持井然有序和干净,我在 app/server/connection.coffee 中添加了一个新文件并编写了这段代码

# in coffee
Meteor.onConnection (connection) ->

  connection.onClose ->

    # Do your stuff

# in javascript
Meteor.onConnection(function(connection) {

  connection.onClose(function() {

    // Do your stuff

  });

});

您可以使用 connection.id 管理数据,这是您浏览器选项卡的唯一标识符。这两种解决方案对我来说都很有效。

If you use Meteor.userId through their accounts system, you can't use it outside a method in the server-side so I had to find a workaround with the connection.id.

如果有人有更好的解决方案来在获取此类客户端数据时管理连接,请不要犹豫,提供您的意见。