使用JavaScript动态设置Primeface的dataGrid中的列数

时间:2014-01-26 22:34:14

标签: javascript jsf jsf-2 primefaces

我正在使用Primefaces的dataGrid,并希望动态设置列数,具体取决于客户端的屏幕宽度。

为了实现这一点,我使用一个脚本,该脚本使用jQuery的$(window).width()来检测屏幕宽度,然后将其作为请求参数发送。在呈现dataGrid之前调用该脚本。

h:outputScript启动接收请求参数的方法,并保存ArrayList中的列数。

然后dataGrids列从arrayList中获取其值,其中保存所有值。

我面临的问题是仅从附加页面刷新应用正确的值。我知道这是由JSF生命周期和部分页面加载引起的。

请告诉我我的错误在哪里,以及纠正错误的最佳方法是什么。

的index.xhtml:

    <script type="text/javascript">
        function win() {
            var width = $(window).width();
            $.post("index.xhtml", {windowWidth: width});
        }
    </script>

...继续

        <section id="main" class="col-lg-10 col-xs-6">
            <h:outputScript value="#{windowController.windowSize()}">win()</h:outputScript>
            <p:dataGrid value="#{productController.fullList}" 
                        var="p" 
                        paginator="true" 
                        rows="9" 
                        lazy="true" 
                        paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"  
                        rowsPerPageTemplate="3,9,15"
                        columns="#{windowController.lastFromList}"
                        id="dataGrid"
                        >
                <p:column>
                    <p:panel header="#{p.name}">
                        <h:outputText value="#{p.price}"/>
                    </p:panel>
                </p:column>   
            </p:dataGrid>
        </section>     

WindowController

@Named
@SessionScoped


private int columns = 1;
private ArrayList<Integer> al;

public WindowController() {
    al = new ArrayList<>();
}

private void addToList(int i) {
    al.add(i);
}

public int getLastFromList() {
    if (!al.isEmpty()) {
        return al.get(al.size() - 1);
    } else {
        return 1;
    }
}

public void windowSize() {
    int width = 0;
    if ((FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("windowWidth")) != null) {
        width = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("windowWidth"));
    } else {
        System.out.println("no param");
    }

    if (width > 1200) {
        addToList(3);
    } else if (width > 500 && width < 1199) {
        addToList(2);
    } else {
        addToList(1);
    }
}

}

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案:

我将一个Javascript放入一个login.xhtml页面,简单的页面,没有多个表单用于评估, - 它没有多次重新渲染,并且脚本在第一次启动时获得实际宽度。所以我只是将其值作为参数传递给bean,由dataGrid的列调用。

就是这样!

相关问题