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

查看:175
本文介绍了使用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,而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()< o:onloadScript> 等。

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天全站免登陆