This is pretty basic, but I had to do a bit of digging to figure out the answer so I wanted to post it. Essentially, since I’m using Mustache.js to load templates, I wanted to find a way to bind events to elements in those templates. My template has a form element and when the form gets submitted, I wanted to handle the data. The JavaScript is easy, especially with jQuery:
$('#beerform').submit(function(e){ var beer_obj = new Object(); $('#beerform :input').each(function(){ beer_obj[this.name] = this.value; }); beers.all(function(arrBeers){ var beer_db_obj = {beername:beer_obj.beername,brewername:beer_obj.brewername,brewerlocation:beer_obj.brewerlocation ,beerstyle:beer_obj.beerstyle,quantity:beer_obj.quantity,purchasedate:beer_obj.purchasedate,price:beer_obj.price ,cellardate:beer_obj.cellardate,cellartemp:beer_obj.cellartemp,brewdate:beer_obj.brewdate}; console.log(beer_db_obj); beers.save({key:arrBeers.length.toString(),value:beer_db_obj}); });
There’s kind of a lot of nastiness going on there, but basically I’m just getting all of the elements from the form that has been submitted, putting them into an object and then preparing them for the database and saving them using Lawnchair. The problem was that I was putting it in the same place I put all of my other JavaScript events, as a separate function inside my app.js file. But when I’d load the page and submit the form, nothing happened. It took me a couple of minutes to figure out what was going on.
Since Mustache doesn’t load things into the DOM right away, I had to make sure the above code was only being added after the Mustache template had loaded. By putting the code within the callback function for the original get() method, which retrieves the template with Ajax, and making sure the template had been injected into the DOM, it worked.
$.get('templates/beer_add.mustache', function(data){ template = data; var renderedhtml = Mustache.to_html(template); $('#content').html(renderedhtml); // the template is now in the DOM $('#beerform').submit(function(e){ var beer_obj = new Object(); $('#beerform :input').each(function(){ beer_obj[this.name] = this.value; }); beers.all(function(arrBeers){ var beer_db_obj = {beername:beer_obj.beername,brewername:beer_obj.brewername,brewerlocation:beer_obj.brewerlocation ,beerstyle:beer_obj.beerstyle,quantity:beer_obj.quantity,purchasedate:beer_obj.purchasedate,price:beer_obj.price ,cellardate:beer_obj.cellardate,cellartemp:beer_obj.cellartemp,brewdate:beer_obj.brewdate}; console.log(beer_db_obj); beers.save({key:arrBeers.length.toString(),value:beer_db_obj}); }); console.log(beer_obj); }); });
Fairly obvious once I figured it out, but I’m still having to remind myself of just how the DOM operates so I don’t run into issues like this.
TweetRelated posts: