我有一个单页、单类的Vaadin项目。在这个项目中,我可能会更改布局,使其看起来好像进入了一个新页面。但由于没有接近新的链接/页面,我无法弄清楚如何让用户“返回”到前一个元素。
有一段时间,我想我可以改变网址,然后捕捉人们是使用前进按钮还是后退按钮。我找到了hashChange事件,但我无法理解它或使它工作。Vaadin有一个历史变更事件处理程序,但它不监听hashChange,因此我的解决方案不起作用。
我在解决这个问题方面做得不够。我从2019年找到了这个线程,这似乎是我问题的解决方案,但我无法使代码正常工作。我想我试图将错误的元素传递给javaScript执行。
因此,我有一个扩展div的简单主视图。在这个div中,我有以下代码:
History history = UI.getCurrent().getPage().getHistory();
TextField textField = new TextField();
add(textField);
Button button = new Button();
button.setText("New link");
button.addClickListener(e-> history.pushState(null, "#"+textField.getValue()));
add(button);
Button button1 = new Button();
button1.setText("Go back");
button1.addClickListener(e-> history.back());
add(button1);
getElement().executeJs(
"const serverCallback = element.$server.onHashChange; this.window.addEventListener('hashchange', function () {serverCallback(location.hash);}, false);"
);
@ClientCallable
public void onHashChange(String hash) {
System.out.print("test "+hash);
}
我预计会调用onHashChange方法。但是我收到一个javascript错误,说:(参考错误):元素未定义。
工作解决方案:
getElement().executeJs("const serverCallback = $0.$server.onHashChange;" +
"window.addEventListener('hashchange', function () {serverCallback(location.hash);}, false);", getElement());
我想我的getElement()是扩展的div。这是我的onHashChange方法。
@ClientCallable
public void onHashChange(String location) {
System.out.println("Current location is: " + location);
}
此外,如果您只想从vaadin调用java方法。您可以执行以下操作:
getElement().executeJs("$0.$server.onHashChange(\"It works\");", getElement());
祝你好运!谢谢埃里克抽出时间帮忙。
查看JavaDoc的执行Js
,它说:
* Asynchronously runs the given JavaScript expression in the browser in the
* context of this element.
* ...
* This element will be available to the expression as <code>this</code>.
因此,请尝试将元素替换为
this.$server
。