我已经从fromwicket站点复制了ListEditor组件,该组件支持在运行时添加项目:
public abstract class ListEditor<T> extends RepeatingView implements IFormModelUpdateListener {
List<T> items;
public ListEditor(String id, IModel<List<T>> model) {
super(id, model);
setOutputMarkupId(true);
}
protected abstract void onPopulateItem(ListItem<T> item);
public void addItem(T value) {
items.add(value);
ListItem<T> item = new ListItem<T>(newChildId(), items.size() - 1);
add(item);
onPopulateItem(item);
}
@Override
protected void onBeforeRender() {
if (!hasBeenRendered()) {
List<T> modelObject = getModelObject();
if (modelObject != null) {
items = new ArrayList<T>(modelObject);
for (int i = 0; i < items.size(); i++) {
ListItem<T> li = new ListItem<T>(newChildId(), i);
add(li);
onPopulateItem(li);
}
} else {
items = new ArrayList<T>();
}
}
super.onBeforeRender();
}
@Override
public void updateModel() {
setModelObject(items);
}
/**
* Indicates whether or not the item can be removed, usually by the use of
* {@link RemoveButton}
*
* @param items
* @param item
* @return
*/
public boolean canRemove(List<T> items, T item) {
return true;
}
@SuppressWarnings("unchecked")
final boolean checkRemove(ListItem<?> item) {
List<T> list = Collections.unmodifiableList(items);
ListItem<T> li = (ListItem<T>) item;
return canRemove(list, li.getModelObject());
}
/**
* Gets model
*
* @return model
*/
@SuppressWarnings("unchecked")
public final IModel<List<T>> getModel() {
return (IModel<List<T>>) getDefaultModel();
}
/**
* Sets model
*
* @param model
*/
public final void setModel(IModel<List<T>> model) {
setDefaultModel(model);
}
/**
* Gets model object
*
* @return model object
*/
@SuppressWarnings("unchecked")
public final List<T> getModelObject() {
return (List<T>) getDefaultModelObject();
}
/**
* Sets model object
*
* @param object
*/
public final void setModelObject(List<T> object) {
setDefaultModelObject(object);
}
}
问题:我希望每次调用刷新都是从零开始构建组件,所以当有人添加项目时,我该如何实现?
答案 0 :(得分:0)
您也可以使用Ajax调用将项添加到普通的ListView中。只需确保将要添加的项目添加到ajaxcall中的基础列表(通常使用LoadableDetachableModel
),然后通过将其添加到AjaxRequestTarget
并设置setReuseItems
来刷新整个列表视图为假。
类似的东西:
LoadableDetachableModel<List<MyObject>> myListModel = new LoadableDetachableModel<List<MyObject>>()
{
public List<MyObject> load()
{
return generateListDynamically(); //or whatever method you use to retrieve the list including the items you've added
}
}
ListView<MyObject> items = new ListView("items", myListModel);
items.setReuseItems(false);
add(items);
//A method you call in the onclick of the link that adds or removes an item.
public void onItemAdd(AjaxRequestTarget target)
{
//should be accessible, maybe make it a member of the page or something
target.add(items);
}