2011-08-20 124 views
5

爲什麼goog.history.Html5History對象在每次更改片段時都會觸發兩次goog.history.EventType.NAVIGATE事件?這是代碼的例子:Google Closure - Html5History兩次觸發NAVIGATE事件

var history = goog.history.Html5History.isSupported() 
     ? new goog.history.Html5History() 
     : new goog.History(); 
goog.events.listen(history, goog.history.EventType.NAVIGATE, function(e) { 
     console.log(['navigation', e.target.getToken()]); 
}); 
history.setEnabled(true); 

這是日誌:

["navigation", "!/properties/new"] 
["navigation", "!/properties/new"] 

UPD:正如我已經想通了,有回調e對象isNavigation場的兩個不同的值。第一次需要false值,第二次需要true值。 isNavigation表示:

isNavigation真,如果該事件是由瀏覽器動作觸發,例如 向前或向後,點擊鏈接,編輯URL,或者調用 的window.history(去|返回|前進。 )。假如令牌已被setToken或replaceToken調用更改爲 ,則爲False。

但是如何讓一個人甚至被解僱?

回答

1

我遇到了同樣的問題。但在我的情況下,這兩個事件都有isNavigation==true

init = function() { 
    var h = goog.history.Html5History.isSupported() ? 
     new goog.history.Html5History() : new goog.History(); 

    goog.events.listen(h, goog.history.EventType.NAVIGATE, navigationCallback); 
    h.setEnabled(true); 
}; 

navigationCallback = function(e) { 
    console.log(e, e.token, e.isNavigation); 
}; 

// And then: 
h.setToken("example1"); 
h.setToken("example2"); 
// And click "back" button in browser 

輸出:

goog.history.Event "example1" false 
goog.history.Event "example2" false 
goog.history.Event "example1" true 
goog.history.Event "example1" true 
+1

在這裏你能找到簡單的補丁: http://code.google.com/p/closure-library/issues/detail?id=449 它移除裝訂Html5History到popstate瀏覽器事件。 –