2011-11-14 5 views
6

Trong dự án gwt, tôi có một CellTree với các ô tùy chỉnh. Để kiểm tra dễ dàng hơn, tôi muốn thêm ID cho mỗi ô. Tôi biết tôi có thể làm cho nó như thế này:Làm cách nào để thêm id duy nhất vào ô tùy chỉnh?

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

Nhưng tôi muốn sử dụng một cái gì đó tương tự như EnsureDebugID() vì vậy tôi không cần phải đốt cháy các ID trong các mã. Có cách nào làm được việc này không?

Trả lời

2

tôi sẽ làm một cái gì đó giữa hai trong số những phương pháp nói trên. Bạn chắc chắn nên thêm tiền tố để chắc chắn bạn có thể dễ dàng xác định các ô trong khi thử nghiệm và bạn cũng nên thực hiện cách tiếp cận createUniqueId() thay vì tạo UUID của riêng bạn, điều này có thể gây phiền toái hơn.

@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

Nói chung khi tôi làm điều này, tôi thêm tiền tố vào nó. vì vậy ID = "sec_22" trong đó sec_ là tiền tố. Sau đó, tôi biết rằng phần có một cái gì đó độc đáo.

1

Bạn có thể sử dụng

Document.get().createUniqueId(); 

Ở đây mô tả:

/** 
    * 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

tôi muốn thiết lập một id để một TextCell và tôi đã làm như thế này

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())); 
     } 
    } 

} 

tôi đặt id bằng với giá trị văn bản.