Using jQuery's data() with Mustache.js templates - javascript

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 set data-answer will only result in the text representation of your answer objects being stored
Another approach you could try is to cache your answer objects in a map (as a JS object) and use your data-answer attribute to store keys into that map.

Related

What does 'data()' do in '$("#myWidget").data(`ejTE`)'

This works:
var editor = $("#htmlEditor").data('ejRTE');
The question is what does .data('ejRTE') do?
It retrieves the widget which is part of this html:
<textarea id="htmlEditor" value.bind="entity.content"
ej-rte="e-width:100%"
ref="textArea"
style="height: 220px"></textarea>
How do I retrieve it without jQuery.
jQuery.data() Store arbitrary data associated with the specified element and/or
return the value that was set.
So basically the widget stores some data in the element htmlEditor indexed ejRTE, I bet it is a custom object used by this tool.
var editor = $("#htmlEditor").data('ejRTE');
then editor will hold the object stored by the widget for this element
If you set data like this $(#myWidget).data('foo', 'myFoo') then jQuery will create an object called 'jQuery224059863907884721222' on myWidget which it uses to store the value.
I am guessing that the number is an arbitrary datetime value.
I stepped through the jQuery code, and it's not practical to replace it. I thought it might be just a line or two of code.

js get elements from array of a serialized form object

Im using JS for a quick web form, all is working fine, I place the responses of the form in a serialized js object into an array,
var myCars = new Array($('#popup-form').serialize());
console.log(myCars);
which gives me on the console:
["name=asfe&email=juan234%40gmail.com&phone=&password=&options=discuss-offer&other=", $family: Object, each: function, clean: function, associate: function, link: function…]
so the question is, this is not behaving like a normal array?
is the array the best way to take the elements?, I tried with mycars[0], but is not working,
Im just coming back to JS!, what is missing to get the elements for the form?, thanks!
jQuery has a serializeArray() method as well.
The .serializeArray() method creates a JavaScript array of objects,
ready to be encoded as a JSON string. It operates on a jQuery object
representing a set of form elements.

Is it possible to store a JSON object directly into the DOM somehow?

If one has the output of a JSON.parse readily at hand, is there some legitimate way of storing that object in the DOM as a single entity?
i.e.
jsonObject = JSON.parse(something);
I'd like to consider storing the jsonObject in the DOM as a (child || textNode || ???) of some element and later retrieving it so that immediately after retrieval I could access its contents via the usual:
jsonObject.keyName
I want to avoid adding dozens of dataset attributes and later being forced to extract them one at a time. That's too much work and seems too inefficient if you have dozens of key:value pairs.
Data attributes have to be strings, you can't store objects in them directly. So don't parse the JSON string, just store the JSON string directly in the dataset attribute.
If you use jQuery, its .data() method will take an object, and it will automatically stringify it as needed.
If the elements you want to associate the object with all have IDs, another option is to use a global object as a table, keyed off the element's ID.
jsonTable[id] = jsonObject;
It depends on the life cycle of your page. If you don't intend to reload the page it's better to just leave it as a JavaScript variable on the page.
You can also consider storing the raw JSON in a hidden filed or some other hidden DOM element. Keep in mind though that hidden fields will be posted to the server if you do a post of the page
TGH has the right answer. Leave it as a variable.
An alternative is to use history.pushState() to store it along with the URL to your page. This is helpful if you ever want the user to be able to click the back button and have the json restored to the value it had for that page.
If you want to store a data (JSON) associated with DOM element.
You could use jQuery data function.
e.g., store a JSON to a restaurant row (div)
$("div.restaurant-row").data("info",{purchases: "blablabla", mealFormulas: "xxxxx"});
e.g., fetch DOM associatd data
$("div.restaurant-row").data("info").purchases; //blablabla
I'm not sure if this is what you want.
Hope this is helpful for you.

append object to innerHTML and get that object from innerHTML

here is an example in jsfiddle.
I want to know if I can append a javascript object to innerHTML, that get that object again from innerHTML as object.
something like,
alert((this.innerHTML).html);
that's just an example, don't ask me why do you need this?
I'm trying to edit an existing code, and I have to do this so.
I have to transfer an object via div.innerHTML.
Check this jsfiddle. In it, I add the object to the div as a 'data-'-attribute, using JSON to convert it to a string. After that, adding some comment to the div triggers the DOMSubtreeModified-handler, in which the 'html'-part of the object is retrieved and alerted. It that something to work with?
In this case, quite possible your only option is to convert your object to string and then put that into the element. (This is done by looping through the key, values building the string as you go.)
You would reverse the process to convert it back into an obj.
I know some javascript libary's have helper functions to make this process very simple.
You could try adding the data directly onto the dom element, rather than as its content..
tempDiv.objData = myObject;
It was suggested to use JSON, but no code. So:
function addObjAsJSON(el, obj) {
el.setAttribute('data-myJSON', encodeURIComponent(JSON.stringify(obj)));
}
function getObjAsJSON(el) {
return JSON.parse(decodeURIComponent(el.getAttribute('data-myJSON')));
}
That should allow you to add anything as a serialised object, then get it back. You should add some error checking to make it robust though (e.g. check that you get a string back from the call to getAttribute).
For user agents that don't have built-in JSON support, see json.org which has a link in the javascript section to json.js.

JSON encoded formatter function name

I'm using jqgrid for which I create column definitions on server as dynamic objects and serialize them using Json.Encode:
html.Raw(System.Web.Helpers.Json.Encode(ColumnDefinition);
I have problem with applying custom formatter, as my serialized column definition is:
{"name":"Icon","index":"Icon","hidden":false,"formatter":"iconFormatter","unformat":{}}
Problem is in quotes which are added to all keys and values to respect JSON specification, and those around iconFormatter are problem in my case as I want that to be my function.
Is there a simple solution for this?
It seems to me that you have the same or close problem as described here. You will have to replace the string values of the formatter properties to the function reference. Pragmatic way is to search for the strings like "iconFormatter" (search for all custom formatters which you use) and replace there to the corresponding function refernce.
UPDATED: If you would be use template property inside of column definition (see here) you would be solve the problem in another way. Additionally you code will be shorter, more clear and better readable.

Categories

Resources