如何向自定义单元格添加唯一ID?

时间:2011-11-14 14:52:37

标签: testing gwt cell

在gwt项目中,我有一个带自定义单元格的CellTree。为了便于测试,我想为每个单元格添加ID。 我知道我可以这样做:

@Override
public void render(Context context,TreeElement value, SafeHtmlBuilder sb) {             
            if (value == null) {return;}
            sb.appendHtmlConstant("<div id=\""+value.getID()+"\">" + 
                                       value.getName()) + "</div>"; 
}

但是我想使用类似于EnsureDebugID()的东西,所以我不必在代码中刻录ID。有没有办法做到这一点?

4 个答案:

答案 0 :(得分:2)

我会在上述两种方法之间做点什么。你绝对应该添加一个前缀,以确保你可以在测试过程中轻松识别单元格,你也应该采用createUniqueId()方法而不是生成自己的UUID,这可能会更麻烦。

@Override
public void render(Context context, TreeElement value, SafeHtmlBuilder sb) {             
    if (value == null) {return;}
    String id = Document.get().createUniqueId();
    sb.appendHtmlConstant("<div id=\"cell_"+id+"\">" + 
                           value.getName()) + "</div>"; 
}

答案 1 :(得分:1)

您可以使用

Document.get().createUniqueId();

这里的描述:

/**
   * Creates an identifier guaranteed to be unique within this document.
   * 
   * This is useful for allocating element id's.
   * 
   * @return a unique identifier
   */
  public final native String createUniqueId() /*-{
    // In order to force uid's to be document-unique across multiple modules,
    // we hang a counter from the document.
    if (!this.gwt_uid) {
      this.gwt_uid = 1;
    }

    return "gwt-uid-" + this.gwt_uid++;
  }-*/;

答案 2 :(得分:0)

通常当我做这种事情时,我会为它添加一个前缀。所以ID =“sec_22”,其中sec_是前缀。然后我知道该部分有一些独特之处。

答案 3 :(得分:0)

我想为TextCell设置一个id,我确实喜欢这个

import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;

public class EnsuredDbgIdTextCell extends TextCell {

    private static EnsuredDbgIdTextCellTemplate template = null;

    public EnsuredDbgIdTextCell() {
        super();
        if (template == null) {
            template = GWT.create(EnsuredDbgIdTextCellTemplate.class);
        }
    }

    public interface EnsuredDbgIdTextCellTemplate extends SafeHtmlTemplates {
        @Template("<div id=\"{0}\" style=\"outline:none;\" tabindex=\"0\">{0}</div>")
        SafeHtml withValueAsDebugId(String value);
    }

    @Override
    public void render(Context context, SafeHtml value, SafeHtmlBuilder sb) {
        if (value != null) {
            sb.append(template.withValueAsDebugId(value.asString()));
        }
    }

}

我将id等于文本值。