I am building a web-application where I want to display a complex model (named Answer). I am using a Mustache template to format the data, but now I have the problem that I cannot attach any complex data to the resulting html, which is normally possible using jQuery’s .data() method.
My current (incorrect) implementation should demonstrate what I am trying to accomplish:
// (part of) the template
{{#answers}}
<input type="checkbox" data-answer="{{.}}">{{text}}
{{/answers}}
// js on the page
$(document).on('change', 'input[type="checkbox"]', function (event) {
console.log($(this).data('answer'));
})
Now I was hoping for a reference to the original Answer-object in the console, instead I got the rather useless string “[object Object]”. Is there some way for me to retrieve the original object when the user checks the checkbox?
Edit: See also http://jsfiddle.net/sebastianv89/jQBpN/
I think the problem may be that HTML
data-attributes are used to store textual data, not actual Javascript objects, so using a Mustache template to attempt to setdata-answerwill only result in the text representation of your answer objects being storedAnother approach you could try is to cache your answer objects in a map (as a JS object) and use your
data-answerattribute to store keys into that map.