2011-11-14 98 views
6

在一個gwt項目中,我有一個帶有自定義單元格的CellTree。爲了便於測試,我想爲每個單元添加ID。 我知道我可以把它像這樣:如何將唯一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東西(),所以我沒有到IDS燃燒中的代碼。有沒有辦法做到這一點?

回答

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>"; 
} 
0

通常當我做這種事情時,我給它添加一個前綴。所以ID =「sec_22」,其中sec_是前綴。然後我知道這個部分有一些獨特的東西。

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++; 
    }-*/; 
0

我想一個ID設置爲TextCell我做了這樣的

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等於文本值。

相關問題