使用 Javascript 获取支持 bean 值 [英] Getting backing bean value with Javascript

查看:17
本文介绍了使用 Javascript 获取支持 bean 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSF 2.0、Mojarra 2.0.1、PrimeFaces 3.4.1

有类似的问题,但我需要……别的;javascript 函数必须等待支持 bean 方法,该方法正在填充想要从 js 函数中提取的变量.我想说的是:

There are similar questions but I need sth. else; javascript function has to wait for the backing bean method, which is filling the variable that wanted to be pulled from js function. What I want to say is:

<p:commandLink action="#{statusBean.getStatuses}" oncomplete="afterLoad()"/>

假设 js 函数只是获取值并将其打印到屏幕上.

Assuming js function just getting the value and printing it to the screen.

function afterLoad() {    
    alert("#{statusBean.size}");
}

这是生日的孩子:

@ManagedBean
@ViewScoped
public class StatusBean {
    public int size=0;
    List<Status> panelList = new ArrayList<Status>();
    public void getStatuses() {
        this.panelList = fillList();
        this.size = panelList.size(); //Assuming 3
    }
    //getter and setters
}

所以函数提醒大小为 0,这是它的初始值,而我们期望看到 3.

So function alerts the size as 0 which is the initial value of it, while we're expecting to see 3.

它是如何工作的:如果我将 @PostConstruct 注释添加到 bean 的头部,它肯定会获得正确的大小,因为 bean 在页面加载之前已经构造好了.但这意味着冗余进程,仅在 commandlink 操作之后需要的值.那么如何推迟js功能呢?有什么想法吗?

How it's working: If I add the @PostConstruct annotation to bean's head surely it gets the correct size, because bean is already constructed before the page load. But this means redundant processes, value just needed after the commandlink action. So how to postpone the js function? Any ideas?

推荐答案

JSF/EL 和 HTML/JS 不同步运行.相反,JSF/EL 在 webserver 中运行并生成 HTML/JS,后者又在 webbrowser 中运行.在浏览器中打开页面,右键单击并查看源代码.你看,没有一行 JSF/EL.它是一种和所有的 HTML/JS.代替您的 JS 函数,您将看到:

JSF/EL and HTML/JS doesn't run in sync. Instead, JSF/EL run in webserver and produces HTML/JS which in turn runs in webbrowser. Open page in browser, rightclick and View Source. You see, there's no single line of JSF/EL. It's one and all HTML/JS. In place of your JS function, you'll see:

function afterLoad() {    
    alert("0");
}

正是在您的命令按钮操作完成时调用此 JS 函数.所以结果完全在意料之中.

Exactly this JS function get invoked on complete of your command button action. So the result is fully expected.

基本上,您希望让 JSF 重新渲染那段 JS.

Basically, you want to let JSF re-render that piece of JS.

<p:commandLink action="#{statusBean.getStatuses}" update="afterLoad" oncomplete="afterLoad()"/>
<h:panelGroup id="afterLoad">
    <h:outputScript>
        function afterLoad() {    
            alert("#{statusBean.size}");
        }
    </h:outputScript>
</h:panelGroup>

根据具体的功能需求,你没有告诉任何东西,可能有更优雅的方式.例如RequestContext#execute()

Depending on the concrete functional requirement, which you didn't tell anything about, there may be more elegant ways. For example, RequestContext#execute(), <o:onloadScript>, etc.

这篇关于使用 Javascript 获取支持 bean 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆