1

我从wicket 站点复制了支持在运行时添加项目的 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);
}
}

问题:我希望每次调用刷新都从零开始构建组件,所以当有人添加一个项目时,我该如何实现呢?

4

1 回答 1

0

您也可以使用 Ajax 调用将项目添加到普通的 ListView。只需确保将要添加的项目添加到 ajaxcall 中的基础列表(通常使用 a ),然后通过将其添加到并设置 为 falseLoadableDetachableModel来刷新整个列表视图。AjaxRequestTargetsetReuseItems

就像是:

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);
}
于 2013-08-27T11:50:35.790 回答