2017-03-31 127 views
1

流星上有客戶端的onConnection鉤子嗎?這是我的問題: 我試圖隨時檢測流星重新連接到服務器以編程方式重新訂閱一些基於參數的數據。流星onConnection客戶端掛鉤?

流星居然自動重新訂閱我的默認訂閱功能,但我也有一個globlal訂閱基於參數,並重新連接後不重新加載:

Meteor.subscribe('Members', fnGetLastEvent()); 

我試着去重新裝入一個流星重新連接鉤,如果存在。 在此先感謝。

+0

您能否將您的全局訂閱參數存儲在'Session'中並在訂閱中使用它(您的訂閱需要被封裝在'autorun'中)。我很確定Meteor會在重新連接時重新運行所有依賴於反應性數據源的反應式計算(例如'Session')。值得一試。 – jordanwillis

回答

2

我沒有直接的答案給你,但這裏有幾件事你可以嘗試看看它們是否適合你的具體用例。

1)在客戶端設置自己的onReconnect回調函數。

Meteor.onReconnect = function() { 
    console.log("meteor has reconnected); 
    // do stuff 
}; 

我在流星應用程序的控制檯中使用Chrome開發人員工具對此進行了測試。我設置了onReconnect回調,運行Meteor.disconnect(),然後運行Meteor.reconnect(),我的回調被觸發。唯一需要注意的是我不確定這個回調是否在連接建立後運行之前運行。

2)將subscribe呼叫放入使用Meteor.status()作爲被動數據源的autorun中。我在我的一個應用程序中做了類似的檢查,以檢查Meteor是否未連接,然後顯示通知用戶其數據不再是實時的模式。這是我用來檢測Meteor何時斷開連接與重新連接的主要邏輯。

var updateCountdownTimeout; 
var nextRetry = new ReactiveVar(0); 

Tracker.autorun(() => { 
    if (Meteor.status().status === 'waiting') { 
    updateCountdownTimeout = Meteor.setInterval(() => { 
     nextRetry.set(Math.round((Meteor.status().retryTime - (new Date()).getTime())/1000)); 
    }, 1000); 
    } else { 
    nextRetry.set(0); 
    Meteor.clearInterval(updateCountdownTimeout); 
    } 

    if (!Meteor.status().connected && Meteor.status().status !== 'offline' && Meteor.status().retryCount > 0) { 
    console.log("Connection to server has been LOST!"); 
    } else { 
    console.log("Connection to server has been RESTORED!"); 
    // put subscription logic here 
    } 
}); 

這裏的警告是我不確定第一次應用程序加載時會發生什麼。我不確定您的訂閱邏輯是否會運行,或者只有在重新連接後才能運行(您可以測試)。

3)這只是理論上的。您似乎應該能夠將您的訂閱參數存儲在Session中,並將您的訂閱邏輯放入autorun。重新連接後,理論上autorun應該再次運行。假設這是在某個模板的內部,那麼它看起來像這樣。

this.autorun(() => { 
    this.subscribe('Members', Session.get('sub_params')); 
}); 

4)有一些回調,你可以設置在client Meteor.connection._stream object,你可能會使用。可用選項爲message,resetdisconnect。我之前使用過message的回調進行調試(見下文)。

Meteor.connection._stream.on('message', function (message) { 
    console.log("receive", JSON.parse(message)); 
}); 

假設上reset被觸發時,重新建立連接,那麼你可能能夠把訂閱的邏輯存在。

Meteor.connection._stream.on('reset', function() { 
    // subscription logic here 
}); 

祝你好運!

+0

你又做了@jordanwillis!我嘗試了你的第4號選擇,現在它正在工作,謝謝!這裏是我的代碼(如果我在重新連接時發生特定路由,我只重新訂閱,否則我在重新切換路由時重新訂閱): 'Meteor.connection._stream.on('reset',function(){ if (Router.current()。route.getName()==「eventContainer.:_id」){ alert(「Reconnected,Ready to subscribe to:」+ Router.current()。params._id); Meteor.subscribe ('Members',Router.current()。params._id); } });' – Ruben

+0

這個@jordanwillis的任何想法? =)http://stackoverflow.com/questions/43241937/publication-receiving-parameter-for-slice-not-refreshing?noredirect=1#comment73592669_43241937 – Ruben

+0

看看我在這個問題上提交的答案。 – jordanwillis