3

I was wondering how I could create "component-scoped" beans, or so-to-say, "local variables inside a composite component" that are private to the instance of the composite component, and live as long as that instance lives.

Below are more details, explained with an example:

Suppose there is a "calculator" component - something that allows users to type in a mathematical expression, and evaluates its value. Optionally, it also plots the associated function.

I can make a composite component that has:

  • a text box for accepting the math expression
  • two buttons called "Evaluate", and "Plot"
  • another nested component that plots the function

It is evidently a self-contained piece of function; so that somebody who wants to use it may just say <math:expressionEvaluator />

But obviously, the implementation would need a java object - something that evaluates the expression, something that computes the plot points, etc. - and I imagine it can be a bean - scoped just for this instance of this component, not a view-scoped or request-scoped bean that is shared across all instances of the component.

How do I create such a bean? Is that even possible with composite components?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Pradyumna
  • 1,583
  • 4
  • 19
  • 34

2 Answers2

1

There is no "per-component instance" scope. But you can still achieve your desired effect.

Use a ViewScoped bean to do the evaluating and plotting - these functions are "stateless" and so are fed by your input.

Your input would be backed by a user supplied bean - in the same way a text box or calendar widget needs an input box bound to a user supplied bean. This holds the data that your "stateless" viewscoped bean acts on.

If you really wanted to keep everything contained in the component, I guess you could back the input with a ViewScoped bean that contains a map keyed by the input id. Not sure if that would work though.

Brian Leathem
  • 4,609
  • 1
  • 24
  • 44
0

Alternatively, you could also build a custom Java based UIComponent. Although these required a ridiculous amount of "moving parts" in JSF 1.x, in JSF 2.0 and Facelets they are actually not that much work to build.

Normally one should maybe be moderate in building custom Java based UIComponents, as for most use cases composite components are easier and more straight-forward. However, Java based UIComponents still have their use and doing actual calculations might be such a use.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140