I'm creating HTML markup in Javascript by concatinating string elements. Something like this:
var makeButton = function (el) {
'use strict';
var config = el.attr("data-config"),
dyn = $.parseJSON(config),
hover = false,
state = 'up',
hrf = '',
...
if (dyn.href) {
hrf = 'href="' + dyn.href + '" ';
}
...
// when all variables have been set, concat
iconspan = dyn.icon ? '<span class="ui-icon ' + icn + icp + ics + '"> </span>' : '';
textspan = '<span class="ui-btn-text">' + txt + '</span>';
innerspan = '<span class="ui-btn-inner">' + textspan + iconspan + '</span>';
btn = '<a data-role="button" data-wrapperels="span" class="ui-btn ' + hvr + cls + '" ' + data_icp + data_thm + data_min + data_inl + '>' + innerspan + '</a>';
return btn;
};
When all is set, I'm returning the string to the calling function, where it is inserted into other strings being created. I'm wondering if it's at all possible to store any information on what I'm creating. Since I'm not instantiating into jQuery (= $( btn )
) I can't add any information using something like data()
.
Question:
So if I have a plain "string", what alternatives do I have (if any) to store information on that string?
So if I have a plain "string", what alternatives do I have (if any) to store information on that string?
None. primitive values can have no properties, so you can't store anything on them. Either you switch to objects, or you store the information in some other static structure where it is identified by the string value (of course your function would need to return distinctive strings then, and garbage-collection is somewhat complicated).
So you could just use String
objects wrapping the strings you want to return. They will have the same behaviour in primitive operations (e.g. concatenation) but you can store additional information on them:
btn = new String(btn);
btn.data = …;
return btn;