Question

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.

Was it helpful?

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.

OTHER TIPS

You can trim it down, but for readability I normally do the exact type of thing you've posted...

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

You could also get rid of the html variable, if you really wanted to, but I think you can go too far with minimizing code.

appendTo() will return the html as a jQuery object so you can find the input elements specified, and then attach a click event handler, all in one hit.

What's about with:

$.each(data, function (i, item) {
    item.Date = internationalDateTime(item.Date);
    var html = Mustache.to_html(template, item);
    html.querySelector('input[name=btnView]').addEventListener('click', function() {
        loadView(item.Id);
    }, false);
    $('#list-container').append(html);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top