Калитка: написание собственных компонентов - PullRequest
2 голосов
/ 19 августа 2010

Я пытаюсь использовать wicket framework для моего проекта, и некоторые вещи с компонентами мне не понятны.

Например, я хочу создать компонент - сетку javascript (jqGrid).Все, что мне нужно:

1. create <table id="#jqGrid1"></table>
2. insert javascript at <head> section: 
<script type="text/javascript">
$(document).ready(function () { $('#jqGrid1').jqGrid()  }); 
</script>

Итак, я создал java-класс JqTable.

package kz.primesource.wicket.component;
import kz.primesource.db.docflow.TableColumn;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.protocol.http.WebApplication;
import org.json.simple.JSONObject;

import java.util.ArrayList;

public class JqTable extends Panel implements IHeaderContributor {
private String id;
private String url;
private String editurl;
private String datatype;
private String mtype;
private String autoencode;
private ArrayList<TableColumn> columns;
private int rowNum;

private ArrayList<Integer> rowList;
private String pager;
private String caption;
private boolean isShrinkToFit;
private int width;
private int height;
private boolean isToolbarVisibile;
private String toolbarPosition;

public JqTable(String id) {
    super(id);
    this.id = id;
}

public void renderHead(IHeaderResponse response) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("width",new Integer(100));
    jsonObject.put("height", new Integer(200));
    String options = jsonObject.toJSONString();

    String contextPath = WebApplication.get().getServletContext().getContextPath();
    response.renderJavascriptReference(contextPath + "/js/jquery.jqGrid.min.js");
    response.renderJavascript("$(document).ready(function() { options = " + options + ";$('#jqGrid" + id + "').jqGrid(options); });", id);
    this.setMarkupId(id);
    this.setOutputMarkupId(true);
}

}

и соответствующий html для этого класса JqGrid.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
<wicket:panel>
    <table id="jqGrid1" style="width:100%;height:200px">
    </table>
</wicket:panel>
</body>
</html>

И я не могу понять, как я могу изменить код компонентов.Т.е. генерировать новый идентификатор для каждой следующей сетки на странице.Я имею в виду, я не могу понять принципы, как изменить html-данные внутри компонента, если внутри друг друга есть не только один тег, но и иерархия тегов.

Ответы [ 2 ]

2 голосов
/ 20 августа 2010

Вы почти у цели, но позвольте калитке управлять своими идентификаторами:

private Component gridComponent;

public JqTable(final String id){
    super(id);
    gridComponent = new WebMarkupContainer("grid").setOutputMarkupId(true);
    add(gridComponent);
}

@Override
public void renderHead(final IHeaderResponse response){
    final String options = "{json}"; // code stripped so I don't need to
                                     // include json in my classpath

    final String contextPath = "context"; // dito with servlet api

    response.renderJavascriptReference(contextPath
        + "/js/jquery.jqGrid.min.js");
    response.renderJavascript("$(document).ready(function() { options = "
        + options + ";$('#" + gridComponent.getMarkupId()
        + "').jqGrid(options); });", gridComponent.getMarkupId());

    // btw wicket has it's own domready mechanism, so you could also write it like this:
    response.renderOnDomReadyJavascript("options = "
        + options + ";$('#" + gridComponent.getMarkupId()
        + "').jqGrid(options);");
}

и HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
<wicket:panel>
    <table wicket:id="grid" style="width:100%;height:200px">
    </table>
</wicket:panel>
</body>
</html>
0 голосов
/ 20 августа 2010

В вашем компоненте вам не нужно менять собственную калитку: id. Идентификатор "jqGrid1" является внутренним для использования. при использовании вашего компонента вы добавляете его в иерархию страниц, используя некоторый «внешний» идентификатор.

пример:

add(new JqTable("table1");

и в html:

<div wicket:id="table1">this gets replaced with the JqTable component</div>

сгенерированный комбинированный вывод будет выглядеть примерно так:

<div wicket:id="table1"> 
   <table id="jqGrid1" style="width:100%;height:200px">
</table>

Итак, вы можете добавить еще одну JqTable, присвоив ей другой идентификатор (таблица2 ...)

надеюсь, что это помогло.

...