JSF2 composite components: are #{cc.childCount} and mutually exclusive?

后端 未结 3 2014
日久生厌
日久生厌 2021-01-18 02:44

I just dont get it: If I want my composite component to insert children, I use but #{cc.childCount}

3条回答
  •  [愿得一人]
    2021-01-18 03:19

    From the cc:insertChildren documentation:

    Any child components or template text within the composite component tag in the using page will be re-parented into the composite component at the point indicated by this tag's placement within the section.

    So by using you actually move the children from the #{cc} component to the component in which you specified , effectively making them (great)* grandchildren of #{cc}. To get easy access to these relocated children, I use a as a parent:

    
        
    
    

    Now you can use #{childContainer.childCount} to get to count the children you specified for your composite component. This solution is a bit fragile though: you can only use your composite component once per view, because of the binding. This problem can of course be solved by binding a FacesComponent bean to your composite component. First the bean:

    package com.stackoverflow.jsfinsertchildrenandcountexample;
    
    import javax.faces.component.FacesComponent;
    import javax.faces.component.UIComponent;
    import javax.faces.component.UINamingContainer;
    
    @FacesComponent(value = "myCompositeComponent")
    public class MyCompositeComponent extends UINamingContainer {
    
        private UIComponent childContainer;
    
        public UIComponent getChildContainer() {
            return childContainer;
        }
    
        public void setChildContainer(UIComponent childContainer) {
            this.childContainer = childContainer;
        }
    }
    

    And now you can bind this class to your composite component:

    
    
    
        
        
    
        
            I have #{cc.childContainer.childCount} children.
            
                
            
        
    
    

    Now you have a composite component with and direct access to these children.

    EDIT: incorporated BalusC comment.

提交回复
热议问题