0
# Utility Functions
1
2
Helper functions for text encoding, DOM hydration, component updates, and other common operations that support the json2html templating system.
3
4
## Capabilities
5
6
### Text Encoding
7
8
Safely encode HTML strings to prevent XSS attacks and ensure proper display of user-generated content.
9
10
```javascript { .api }
11
/**
12
* Encodes HTML string to text by escaping HTML entities
13
* @param {string|null|undefined} html - HTML string to encode, null, or undefined
14
* @returns {string} Text with HTML entities escaped, empty string for null/undefined
15
*/
16
function toText(html);
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const json2html = require('node-json2html');
23
24
// Basic HTML encoding
25
const userInput = '<script>alert("XSS")</script>';
26
const safe = json2html.toText(userInput);
27
console.log(safe);
28
// Result: "<script>alert("XSS")</script>"
29
30
// Handle various data types
31
console.log(json2html.toText("Hello & goodbye")); // "Hello & goodbye"
32
console.log(json2html.toText("<div>content</div>")); // "<div>content</div>"
33
console.log(json2html.toText(null)); // ""
34
console.log(json2html.toText(undefined)); // ""
35
console.log(json2html.toText(123)); // "123"
36
37
// Use in templates for safe text display
38
const template = {
39
"<>": "div",
40
"html": [
41
{ "<>": "h3", "text": "User Comment" },
42
{ "<>": "p", "html": json2html.toText("${userComment}") }
43
]
44
};
45
46
const data = { userComment: '<script>malicious()</script>' };
47
const html = json2html.render(data, template);
48
// User comment is safely encoded in output
49
```
50
51
### DOM Hydration
52
53
Attach events and update triggers to existing DOM elements, typically used after server-side rendering or manual DOM manipulation.
54
55
```javascript { .api }
56
/**
57
* Hydrates DOM elements with their events and update triggers
58
* @param {Element|Element[]} parent - Element or array of elements to hydrate
59
* @param {object} events - Event handlers object from iHTML rendering
60
* @param {object} triggers - Update triggers object from iHTML rendering
61
* @returns {object} this for method chaining
62
*/
63
function hydrate(parent, events, triggers);
64
```
65
66
**Usage Examples:**
67
68
```javascript
69
// Server-side rendering scenario
70
const template = {
71
"<>": "button",
72
"text": "Click me",
73
"onclick": function(e) { alert("Clicked!"); },
74
"#": "button-trigger"
75
};
76
77
// Get iHTML output with events and triggers
78
const ihtml = json2html.render({}, template, { output: "ihtml" });
79
80
// On the client side, inject the HTML
81
document.getElementById('container').innerHTML = ihtml.html;
82
83
// Then hydrate to attach events and triggers
84
const element = document.getElementById('container').firstElementChild;
85
json2html.hydrate(element, ihtml.events, ihtml.triggers);
86
87
// Now the button will work with click handlers and update triggers
88
89
// Hydrate multiple elements
90
const elements = document.querySelectorAll('.needs-hydration');
91
json2html.hydrate(Array.from(elements), ihtml.events, ihtml.triggers);
92
```
93
94
### Component Updates
95
96
Trigger dynamic updates of components that have been marked with trigger IDs.
97
98
```javascript { .api }
99
/**
100
* Triggers component update by ID
101
* @param {string} id - Required trigger ID of component(s) to update
102
* @param {object} [obj] - Optional new data object to use for update
103
*/
104
function refresh(id, obj);
105
106
/**
107
* @deprecated Use refresh() instead
108
* Legacy alias for refresh function
109
*/
110
function trigger(id, obj);
111
```
112
113
**Usage Examples:**
114
115
```javascript
116
// Set up components with trigger IDs
117
const template = {
118
"<>": "div",
119
"#": "user-status", // Trigger ID
120
"class": "status-${status}",
121
"html": [
122
{ "<>": "span", "text": "${name}" },
123
{ "<>": "span", "class": "indicator", "text": "(${status})" }
124
]
125
};
126
127
const users = [
128
{ name: "Alice", status: "online" },
129
{ name: "Bob", status: "offline" }
130
];
131
132
// Render with DOM integration
133
document.getElementById('user-list').json2html(users, template);
134
135
// Update all elements with trigger ID "user-status"
136
setTimeout(() => {
137
json2html.refresh("user-status", [
138
{ name: "Alice", status: "busy" },
139
{ name: "Bob", status: "online" }
140
]);
141
}, 3000);
142
143
// Update with original data (uses stored reference)
144
setTimeout(() => {
145
users[0].status = "away";
146
json2html.refresh("user-status"); // Uses original users array
147
}, 6000);
148
149
// Multiple triggers for different components
150
const dashboardTemplate = {
151
"<>": "div",
152
"html": [
153
{
154
"<>": "div",
155
"#": "user-count",
156
"text": "Users: ${userCount}"
157
},
158
{
159
"<>": "div",
160
"#": "message-count",
161
"text": "Messages: ${messageCount}"
162
}
163
]
164
};
165
166
// Update specific parts independently
167
json2html.refresh("user-count", { userCount: 150 });
168
json2html.refresh("message-count", { messageCount: 1250 });
169
```
170
171
### Version Information
172
173
Access the current version of the json2html library for compatibility checking and debugging.
174
175
```javascript { .api }
176
/**
177
* Current version of the json2html library
178
* @type {string}
179
*/
180
const version: string;
181
```
182
183
**Usage Examples:**
184
185
```javascript
186
const json2html = require('node-json2html');
187
188
// Check library version
189
console.log('json2html version:', json2html.version); // "3.3.3"
190
191
// Version compatibility checking
192
function checkCompatibility() {
193
const requiredVersion = '3.0.0';
194
const currentVersion = json2html.version;
195
196
if (currentVersion < requiredVersion) {
197
throw new Error(`json2html ${requiredVersion} or higher required, found ${currentVersion}`);
198
}
199
}
200
201
// Feature detection based on version
202
function hasFeature(feature) {
203
const version = json2html.version;
204
const major = parseInt(version.split('.')[0]);
205
206
switch (feature) {
207
case 'iHTML':
208
return major >= 3;
209
case 'components':
210
return major >= 2;
211
default:
212
return true;
213
}
214
}
215
216
// Debug information
217
function getDebugInfo() {
218
return {
219
version: json2html.version,
220
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'Node.js',
221
timestamp: new Date().toISOString()
222
};
223
}
224
```
225
226
### Error Handling
227
228
Utility functions handle various error conditions gracefully and provide meaningful feedback.
229
230
```javascript { .api }
231
/**
232
* Common error scenarios and handling
233
*/
234
// toText handles null/undefined gracefully
235
json2html.toText(null); // Returns ""
236
json2html.toText(undefined); // Returns ""
237
238
// render handles missing data gracefully
239
json2html.render(null, template); // Returns ""
240
json2html.render(undefined, template); // Returns ""
241
242
// refresh handles missing trigger IDs gracefully
243
json2html.refresh("non-existent-id"); // No error, no action
244
245
// hydrate handles missing elements gracefully
246
json2html.hydrate(null, events, triggers); // No error, no action
247
```
248
249
**Error Handling Examples:**
250
251
```javascript
252
// Safe rendering with error handling
253
function safeRender(data, template, options = {}) {
254
try {
255
if (!data || !template) {
256
return '';
257
}
258
259
return json2html.render(data, template, options);
260
} catch (error) {
261
console.error('Rendering error:', error);
262
return '<div class="error">Rendering failed</div>';
263
}
264
}
265
266
// Safe text encoding
267
function safeText(input) {
268
if (input === null || input === undefined) {
269
return '';
270
}
271
272
return json2html.toText(String(input));
273
}
274
275
// Safe component updates with validation
276
function safeRefresh(triggerId, data) {
277
if (!triggerId || typeof triggerId !== 'string') {
278
console.warn('Invalid trigger ID provided to refresh');
279
return;
280
}
281
282
try {
283
json2html.refresh(triggerId, data);
284
} catch (error) {
285
console.error('Refresh error:', error);
286
}
287
}
288
289
// Safe hydration with element validation
290
function safeHydrate(elements, events, triggers) {
291
if (!elements) {
292
return;
293
}
294
295
const elementArray = Array.isArray(elements) ? elements : [elements];
296
const validElements = elementArray.filter(el => el && el.nodeType === Node.ELEMENT_NODE);
297
298
if (validElements.length > 0) {
299
json2html.hydrate(validElements, events || {}, triggers || {});
300
}
301
}
302
```
303
304
### Performance Considerations
305
306
Utility functions are optimized for performance but should be used appropriately for best results.
307
308
```javascript { .api }
309
/**
310
* Performance best practices
311
*/
312
// Batch refresh operations instead of individual calls
313
// Good:
314
json2html.refresh("user-list", updatedUsers);
315
316
// Avoid:
317
users.forEach(user => {
318
json2html.refresh("user-" + user.id, user);
319
});
320
321
// Cache encoded text for reuse
322
const encodedTexts = new Map();
323
function getCachedText(input) {
324
if (!encodedTexts.has(input)) {
325
encodedTexts.set(input, json2html.toText(input));
326
}
327
return encodedTexts.get(input);
328
}
329
330
// Hydrate once after batch DOM updates
331
const ihtml = json2html.render(data, template, { output: "ihtml" });
332
container.innerHTML = ihtml.html;
333
json2html.hydrate(container, ihtml.events, ihtml.triggers);
334
```