Reputation: 727
So I'm learning dart and web development in general. Right now I'm experimenting with the history API. I have:
import 'dart:html';
void main() {
ParagraphElement paragraph = querySelector('.parag');
ButtonElement buttonOne = querySelector('.testaja');
buttonOne.onClick.listen((_) {
window.history.pushState(null, 'test title', '/testdata/');
window.history.forward();
});
ButtonElement buttonTwo = querySelector('.testlagi');
buttonTwo.onClick.listen((_) {
window.history.back();
});
window.onPopState.listen((_) {
window.alert(window.location.pathname);
});
}
My conclusion is that onPopState
only triggers when we click on browser's back or forward button, or using window.history.forward()
or window.history.back()
. So this is like, we render a template, then change its url using pushState
, not update template based on url changes. Is this true or not?
Edit:
So maybe I'm not clear enough. Let's say I have something like this:
void main() {
InputElement input = querySelector('.input')
ButtonElement changeUrl = querySelector('.change-url');
changeUrl.onClick.listen((event) {
window.history.pushState(null, 'test tile', input.value);
});
Map urls = {
'/' : showRoot,
'/user/:id' : showUserProfile
};
window.onPopState.listen((_) {
var location = window.location.pathname;
urls[location]();
});
}
I can get input
's value by clicking on changeUrl
, and then by adding a listener to changeUrl
, I can use pushState
to update url on browser. What I'm expecting is, when I do pushState
, the window.onPopState
will triggered and invoke the callback when in reality it doesn't.
tldr, what I'm trying to achieve is:
listen on url changes -> get current url -> use current url to invoke a handler stored in a map. Using onHashChange
also doesn't work when updating url using pushState
prefixed by #
.
Upvotes: 1
Views: 476
Reputation: 657546
edit
set the hash using
window.location.hash = input.value;
this triggers the PopState
and HashChange
event
as does a click on such a link
<a href="#abc">abc</a>
original
I don't have time to take a close look what you'r trying to achive..
But I think you should add an event handler for 'window.onHashChange' this way ordinary links work too for navigation, not only buttons with onclick-handlers modifying browser history.
Upvotes: 1