Search code examples
javascriptjqueryunobtrusive-javascript

Unobtrusive jQuery Set Attributes Before Append - Is More Effecient Syntax Possible?


The basic process for this code is:

  • $.get a Mustache template
  • $.getJSON some data from the API
  • Then the code below to process on the client
$.each(data, function (i, item) {
    item.Date = internationalDateTime(item.Date );
    var html = Mustache.to_html(template, item);
    var $html = $(html);
    $html.find('input[name=btnView]').attr('onclick', 'loadView(' + item.Id + ')');
    $('#list-container').append($html);
});

Is there a better way (read more succinct I guess) of doing this without the need for the $html variable?

Not wanting to obsess over "one liners" in my code but it just looks a bit wrong to me.


Solution

  • before adding your html to the DOM, you can do this:

    $(document).on("click", "#list-container input[name=btnView][itemId]", function(){
        loadView($(this).attr("itemId"));
    });
    

    then just add your html to the page like this, the only point here is to store the item.Id:

    $.each(data, function (i, item) {
        item.Date = internationalDateTime(item.Date );
        $(Mustache.to_html(template, item)).appendTo('#list-container')
            .find("input[name=btnView]").attr("itemId", item.Id);
    
    });
    

    your problem this way is just to get access to item.Id.