2017-01-12 91 views
0

我目前有一個使用Turbolink的Rails應用程序。在這個應用程序中,我試圖追蹤在特定視圖上花費的時間。我已經看過無數的問題,並通過名爲window.onbeforeunload,window.beforeunload,window.on(「beforeunload」)的多個變型了......我現在的嘗試是這樣的:Rails w/Turbolinks window.onbeforeunload

$(document).ready(function() { 

var start = Date.now(); 

var id = gon.subjId; 
var rand_index = gon.randIndex; 
var index = gon.index; 

console.log('showing article ' + index + ' at index ' + rand_index + ' for ' + id); 

$(document).on('turbolinks:before-change', function() { 
    $.post('/log', {subj_id: id, article: {index: index, rand_index: rand_index, time_spent: Date.now()-start}}, 
    function(response) { 
    }); 
}) 

});

我知道使用AJAX請求的函數有效;但是,它不叫。如何在後退按鈕被按下時調用此函數?

+0

我認爲Rails的5改變了turbolinks'事件的命名空間'turbolinks'而不是'頁面'嘗試使用'turbolinks:before-change' – ErvalhouS

+0

我試過並更新了這個問題,但它仍然不起作用 – genghiskhan

+0

'turbolinks:load'now有一個'event.data.timing',不是它是你期待看到的日期?請參閱此[鏈接](https://github.com/turbolinks/turbolinks#full-list-of-events) – ErvalhouS

回答

0

我仍然不知道什麼是根本錯誤是,但我改變了腳本這一點,就像一個魅力:

$(document).ready(function() { 
var start = Date.now(); 

var id = gon.subjId; 
var rand_index = gon.randIndex; 
var index = gon.index; 

console.log('showing article ' + index + ' at index ' + rand_index + ' for ' + id); 

function logVisit() { 
    console.log('logging visit'); 

    $.post('/log', {subj_id: id, article: {index: index, rand_index: rand_index, time_spent: Date.now()-start}}, 
    function(response) { 
    }); 
    document.removeEventListener('turbolinks:before-cache', logVisit); 
} 

document.addEventListener('turbolinks:before-cache', logVisit); 
});