Javascript template and event handling

I asked a question about how to avoid writing html in js, then some people tell me using a javascript template like jQuery / pugin template and ect.

This is a good idea when creating static html, for example:

<ul id="productList"></ul>

<script id="productTemplate" type="text/x-jquery-tmpl">
    <li><a>${Name}</a> (${Price})</li>
</script>

<script type="text/javascript">
    var products = [
        { Name: "xxx", Price: "xxx" },
        { Name: "yyy", Price: "xxx" },
        { Name: "zzz", Price: "xxx" }
    ];

    // Render the template with the products data and insert
    // the rendered HTML under the "productList" element
    $( "#productTemplate" ).tmpl( products )
        .appendTo( "#productList" );
</script>

However, when I try to associate an event with the generated html, I encounter some problem.

For example, I have a page where a user can search for some products by price / name / location.

So, I have three functions:

searchByPrice(lowPrice,highPrice,productType,currentPage)
searchByName(name,productType,currentPage);
searchByLocation(location,currentpage);

The ALl of the above function has an implemented method on the server side, and they will extract the products in xml format.

Since they will extract so many elements, so I need to swap them, "currengPage" is used to tell the server side which part of the results should be returned.

, js int div , .

, ( , ):

function searchByPrice(lowPrice,highPrice,productType,currentPage){
    var url="WebService.asmx/searchByPrice?low="+lowPrice="&high="+highPrice+"&curPage="+currentPage;
    //code to create the xmlHttp object
    xmlhttp.open("GET",url,true);
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var i=0;
            var Prohtml="";
            var proList=parseProductList(xmlhttp.responseText);
            for(i=0;i<prolist.length;i++){
                Prohtml+="<li><a href='#'>"+prolist[i].name+"</a> ("+prolist[i].price"+)</li>";
            }


            //generate the paging bar:
            var totleResult=getTotleResultNumber(xmlhttp.responseText);
            if(totleResult>10){
                var paghtml="<span>";
                //need the paging
                var pagNum=totleResult/10+1;
                for(i=1;i<=pagenum;i++){
                    paghtml+="<a onclick='searchByPrice(lowPrice,highPrice,productType,currentPage+1)'>i</a>";
                    //here the synax is not right,since I am really not good at handle the single or doule '"' in this manner.

                    //also if in the searchByName function,the click function here should be replaced using the searchByName(...)


                }

            }
        }
    }

}

"Prohtml", , "paghtml", click differnt.

, , ?

+3
2

:

DOM HTML, document.createElement , , .

, , , , HTML .

:.

var eventHandlers = []
  , eventCount = 0;

for (i = 1; i <= pagenum; i++) {
    var id = "search" + eventCount++;
    html += "<a id='" + id + "'>" + i + "</a>";
    eventHandlers.push([id, 'click',
                        handler(searchByPrice, lowPrice, highPrice, productType, currentPage + i)])
}

// Later...
someElement.innerHTML = html;
registerEvents(eventHandlers);

registerEvents:

function registerEvents(eventHandlers) {
  for (var i = 0, l = eventHandlers.length; i < l; i++) {
    var eventHandler = eventHandlers[i],
        id = eventHandler[0],
        eventName = eventHandler[1],
        func = eventHandler[2];
    // Where addEvent is your cross-browser event registration function
    // of choice...
    addEvent(document.getElementById(id), eventName, func);
  }
}

handler - , :

/**
 * Creates a fnction which calls the given function with any additional
 * arguments passed in.
 */
function handler(func) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function() {
    func.apply(this, args);
  }
}

- ( , ) HTML DOMBuilder, HTML , , innerHTML , . , DOM HTML.

+3

, $.get() $.ajax() AJAX.

-, .live() .delegate() , .

-, , . .data().

, , - :

function searchByPrice(event) {
    $this = $(this);
    var lowPrice = $this.data('lowPrice'),
        highPrice = $this.data('lowPrice'), 
        productType = $this.data('productType'),
        currentPage = $this.data('currentPage');

    var url = "WebService.asmx/searchByPrice?low=" + lowPrice = "&high=" + highPrice + "&curPage=" + currentPage;

    $.get(url, function(data, textStatus, jqXHR) {
        var i = 0;
        var Prohtml = "";
        var proList = parseProductList(data);
        for (i = 0; i < prolist.length; i++) {
            Prohtml += "<li><a href='#'>" + prolist[i].name + "</a> (" + prolist[i].price "+)</li>";
        }

        //generate the paging bar:
        var totleResult = getTotleResultNumber(data);
        if (totleResult > 10) {
            var paghtml = "<span>";

            //need the paging
            var pagNum = totleResult / 10 + 1;
            for (i = 1; i <= pagenum; i++) {
                paghtml += '<a class="pagelink" ' +
                    'data-lowPrice="' + lowPrice + '" ' +
                    'data-highPrice="' + highPrice + '" ' +
                    'data-productType="' + productType + '" ' +
                    'data-currentPage="' + (currentpage + 1) + '">' + i + '</a>';
                //here the synax is not right,since I am really not good at handle the single or doule '"' in this manner.

                //also if in the searchByName function,the click function here should be replaced using the searchByName(...)

            }
        }
    });
}


$(document).ready(function(){
    $("a.pagelink").live('click', searchByPrice);
});
+3

All Articles