开发者

Refactor code to remove uuid

Hi I have some code generated inside a JSP tag, which uses the jQuery data function to associate data with a div.

I have used a UUID to link the jQuery script to the div on the page. However this approach is ugly and inconvenient and I was wondering if there was a way to refactor it to not require the UUID.

The code looks like this.

    for(DomainObject domainObject : domainObjects){
//...
        String uuid = UUID.randomUUID().toString();

        out.println("<div id='" +uuid + "' class='" + divClass + "'>");

        /开发者_如何转开发/ Write out the details of this domain object.
        out.println(/*...*/);

        // Associate data with the div
        out.println("<script type='text/javascript'>$('#"+uuid+"').data('domainObject'," + jsonSerializer.exclude("class").serialize(domainObject) + ")</script>");
        out.println("</div>");
//...
    }


If you are able to use jQuery 1.4.3 there is a very easy way to associate data to an element in the dom. As of 1.4.3 jQuery will inspect the elements for any data attributes and automatically make them available via .data("key")

<div class='myClass' data-domainObject='{"Name": "I am in your data!"}'>
    Domain Object
</div>

$(function(){
    alert($(".myClass").data("domainObject").Name);
});

Example on jsfiddle

Since it appears you are just using the script tag to add data to the element this option might be suitable and look something like this (note I have no experience with jsp):

for(DomainObject domainObject : domainObjects){
//...

        out.println("<div class='" + divClass + "' data-domainObject='" + jsonSerializer.exclude("class").serialize(domainObject)+ "'>");

        // Write out the details of this domain object.
        out.println(/*...*/);
        out.println("</div>");
//...
    }


Two ways (examples are using JSTL/EL)

  1. Use ID of domain object instead, if any.

    <div id="do_${domainObject.id}">
    ...
    <script>$('#do_${domainObject.id}').foo();</script>
    
  2. Use a loop counter.

    <c:forEach items="${domainObjects}" var="domainObject" varStatus="loop">
        <div id="do_${loop.index}">
        ...
        <script>$('#do_${loop.index}').foo();</script>
    </c:forEach>
    

Note that the ID must start with an alphabetic character. ID's starting with a digit are illegal. UUID may return ID's starting with a digit.


Not sure what is so ugly about it. Maybe you just want a shorter id?

A UUID is unique universally. This far exceeds the requirements for IDs on elements in an HTML page - that they are unique within the page.

It is easy and appropriate to create page-unique IDs that are 1 or 2 digits long. Your JSP needs to replace randomUUID() with randomPageId(), which returns a sequence of d1, d2, d3, or whatever.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜