如何在Meteor中使用客户端重新连接事件

Har*_*rry 3 reconnect meteor

如何在Meteor中使用客户端重新连接事件.

在客户端上,Meteor.apply采用新的等待选项,确保在此方法完成之前不再向服务器发送进一步的方法调用; 它用于登录和注销方法,以保持用户ID定义良好.您还可以指定在重新建立连接时运行的onReconnect处理程序; Meteor Accounts使用它来重新连接重新登录.

有人可以提供一个例子.

这是帐户包中的示例.

  Accounts._makeClientLoggedIn = function(userId, token) {
    Accounts._storeLoginToken(userId, token);
    Meteor.default_connection.setUserId(userId);
    Meteor.default_connection.onReconnect = function() {
      Meteor.apply('login', [{resume: token}], {wait: true}, function(error, result) {
        if (error) {
          Accounts._makeClientLoggedOut();
          throw error;
        } else {
          // nothing to do
        }
      });
    };
    userLoadedListeners.invalidateAll();
    if (currentUserSubscriptionData) {
      currentUserSubscriptionData.handle.stop();
    }
    var data = currentUserSubscriptionData = {loaded: false};
    data.handle = Meteor.subscribe(
      "meteor.currentUser", function () {
        // Important! We use "data" here, not "currentUserSubscriptionData", so
        // that if we log out and in again before this subscription is ready, we
        // don't make currentUserSubscriptionData look ready just because this
        // older iteration of subscribing is ready.
        data.loaded = true;
        userLoadedListeners.invalidateAll();
      });
  };
Run Code Online (Sandbox Code Playgroud)

我假设您不能只定义另一个default_connection.onReconnect,如果您希望帐户仍然有效吗?

谢谢.

编辑:

考虑一下,而不是使用onReconnect你可能应该使用Meteor.status()而不是?

Tim*_*Dog 7

哈利,我在上面看到了你的评论并做了这个改变.我认为你是对的.因为Meteor.status是一个反应变量,所以当连接状态改变时,它将重新运行.

if (Meteor.isClient) {
    Tracker.autorun(function () {
        if (Meteor.status().connected) {
            console.log("connected");
        } else {
            console.log("disconnected");
        }
    });
}
Run Code Online (Sandbox Code Playgroud)