2

我使用组件绑定和 clientId 属性在我的 javascript 代码中查找组件,如下所示:

<div data-for="@parent" data-example="#{componentBindings.myInput.clientId}" />
...
<h:inputText binding="#{componentBindings.myInput}" value="#{myBean.myProperty}" />

唯一的问题是 jsf 有时不会呈现 inputText 字段的 id 属性,所以即使我知道 js 代码中的 clientId ,我也找不到该元素,因为它在客户端没有 id 属性。

  1. 渲染自动生成的id 标签有什么要求?
  2. 有什么方法可以让 jsf 自动渲染所有的 cliendId-s?(如 faces-config 条目)
  3. 有什么方法可以确保呈现单个元素的 clientId(没有明确地给它一个 id)?

更新

我找到了使用技巧的方法:

<span id="#{componentBindings.myInput.clientId}">
    <h:inputText binding="#{componentBindings.myInput}" value="#{myBean.myProperty}" />
</span>

尽管在这种情况下有更好的方法,例如使用建议的名称,但如果它不是您希望使用 ajax 呈现的输入字段,它会很有用。例如与方面:

<!-- myComponent.xhtml -->
<!-- ... -->
<cc:interface>
    <cc:facet name="someFacet" required="true" />
</cc:interface>
<cc:implementation>
    <h:form>
        <cc:renderFacet name="someFacet"/>
    </h:form>
</cc:implementation>

<!-- page.xhtml -->
<!-- ... -->
<my:myComponent>
    <f:facet name="someFacet">
        <h:inputText />
        <!-- ... -->
    </f:facet>
</my:myComponent>

如果您查看组件树,您会看到,构面没有嵌套在表单中,它是 cc 的直接子代。所以用ajax执行cc会很好:

<!-- myComponent.xhtml -->
<!-- ... -->
<cc:interface>
    <cc:facet name="someFacet" required="true" />
</cc:interface>
<cc:implementation>
    <h:form>
        <cc:renderFacet name="someFacet"/>
        <h:commandLink>
            <f:ajax execute=":#{cc.clientId}" render=":#{cc.clientId}" />
        </h:commandLink>
    </h:form>
</cc:implementation>

但这会引发格式错误的 xml 异常,因为在客户端没有具有请求 id 的元素。使用此技巧,您可以使其工作:

<cc:interface>
    <cc:facet name="someFacet" required="true" preferred="true"/>
</cc:interface>

<cc:implementation>
    <span id=#{cc.clientId}>
        <h:form>
            <cc:renderFacet name="someFacet"/>
            <h:commandLink>
                <f:ajax execute=":#{cc.clientId}" render=":#{cc.clientId}" />
            </h:commandLink>
        </h:form>
    </span>
</cc:implementation>

我可能不是第一个发现这个解决方法的人,但我决定分享它,因为我在任何地方都没有找到它

4

1 回答 1

1

来自 Mojarra 的HtmlBasicRenderer源代码(从 2.1.17 的第 672 行开始):

/**
 * @param component the component of interest
 *
 * @return true if this renderer should render an id attribute.
 */
protected boolean shouldWriteIdAttribute(UIComponent component) {

    // By default we only write the id attribute if:
    //
    // - We have a non-auto-generated id, or...
    // - We have client behaviors.
    //
    // We assume that if client behaviors are present, they
    // may need access to the id (AjaxBehavior certainly does).

    String id;
    return (null != (id = component.getId()) &&
                (!id.startsWith(UIViewRoot.UNIQUE_ID_PREFIX) ||
                    ((component instanceof ClientBehaviorHolder) &&
                      !((ClientBehaviorHolder)component).getClientBehaviors().isEmpty())));
}

id因此,它仅在组件具有id属性集或组件具有客户端行为持有者(阅读:<f:ajax>子级)时才呈现 HTML 元素的属性。

所以,你真的需要自己指定:

<h:inputText id="foo" ... />

否则,请更改您的 JS 代码,使其通过输入name而不是id.

于 2013-01-28T16:40:05.203 回答