JSFiddle - React, Tailwind, and code Playground

by sidouglas

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<section></section>

JavaScript

var data = {
"recipes":[
{"name": "A", preparationTime: "40min", "servings": "3", "image": "http://placehold.it/120x60/ff0000"},
{"name": "B", preparationTime: "30min", "servings": "2", "image": "http://placehold.it/120x60/ffff00"},
{"name": "C", preparationTime: "20min", "servings": "3", "image": "http://placehold.it/120x60/ffffff"},
{"name": "D", preparationTime: "30min", "servings": "4", "image": "http://placehold.it/120x60/000000"}
]};

var recipeTemplate = "<div class='col-6 recipeUnit'>" +
"<div class='recipeItem row'>" + 
"<div class='recipeItem__image col-5'><img src='{{image}}' alt='recipe image'></div>" +
"<div class='recipeItem__description col-7'>" + 
"<h3 class='recipeTitle'>{{name}}</h3>" + 
"<div class='details'>" +
"<span>{{preparationTime}}</span>" +
"<span>{{servings}}</span>" +
"</div>" +
"<a class='buttonDetails' href='#'>see more ( visual reference: {{name}}  )</a>" +
"</div>" +
"</div>" +
"</div>";

$(document).ready(function(){
		var $section = $('section');
    loadRecipes();
    function loadRecipes(){
						
            var solution = [];

            for(var i = 0; i < data.recipes.length; i++){
                var $button;
                var recipe = data.recipes[i];
                var html = Mustache.to_html(recipeTemplate, recipe);
                $section.append(html);
                $button = $(".recipeUnit:last .buttonDetails"); // get the last $button every time...
                $button.data.recipe = recipe;

                // capture each $button and store it in array. By doing so we ensure we don't reasign the button.
								solution[i] = $button;   
                solution[i].data('recipe',recipe);
           };

         // $button here is going to be the D button, because $button is assigned 4 times.
          $button.on("click",function(){
		       console.log('This is wrong, because the $button variable is repointed on every iteration',$(this).data.recipe);
   			     return false;
	       });  
  				
          //...