【问题标题】:Vaadin 14.4.0 manipulate the back/forward history buttons (onHashChange perhaps)Vaadin 14.4.0 操作后退/前进历史按钮(可能是 onHashChange)
【发布时间】:2020-10-19 11:13:52
【问题描述】:

我有一个单页、单类 Vaadin 项目。在这个项目中,我可能会更改布局以使其看起来好像进入了一个新页面。但由于没有接近新的链接/页面,我无法弄清楚如何让用户“返回”到上一个元素。

有一阵子,我想我可以更改 url,然后了解人们是否使用了前进或后退按钮。我找到了 hashChange 事件,但我无法理解它或使它起作用。 Vaadin 有一个 HistoryChangeEventHandler,但它不监听 hashChanges,因此我的解决方案不起作用。

我无法解决这个问题。我从 2019 年找到了 this thread,这似乎是我的问题的解决方案,但我无法使代码正常工作。我想我正在尝试将错误的元素传递给 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 错误消息:(ReferenceError) : element is not defined。

工作解决方案:

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());

祝你好运!感谢 Erik 抽出时间提供帮助。

【问题讨论】:

    标签: javascript java vaadin


    【解决方案1】:

    查看executeJs 的JavaDoc,它说:

     * 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>.
    

    所以尝试将element.$server 替换为this.$server。

    【讨论】:

    • 一旦我改成那样。我收到此错误:“(TypeError):this.window is undefined”。
    • 从this.window中删除this.。
    • 它工作了一会儿。现在它给我提供了这个错误“(TypeError) : this['}p'] is undefined”。
    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2011-12-31
    • 2015-10-11
    • 2023-03-24
    相关资源
    最近更新 更多