luci-base: cbi.js: add heuristics to attribute handling in E()
authorJo-Philipp Wich <jo@mein.io>
Mon, 5 Nov 2018 10:11:46 +0000 (11:11 +0100)
committerJo-Philipp Wich <jo@mein.io>
Mon, 5 Nov 2018 10:11:46 +0000 (11:11 +0100)
If a given attribute value is a function, register it as event listener,
if it is an object, filter it through JSON.stringify(), else set it
as-is.

This helps to reduce some boiler-plate code when building DOM structures.

Signed-off-by: Jo-Philipp Wich <jo@mein.io>
modules/luci-base/htdocs/luci-static/resources/cbi.js

index 3ace96f32250250620e9f71a8c7b6577a616c1d3..d9b9baf7be9f500c6209cd72a491d8ebaf1626b7 100644 (file)
@@ -1506,7 +1506,18 @@ function E()
        if (attr)
                for (var key in attr)
                        if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
-                               elem.setAttribute(key, attr[key]);
+                               switch (typeof(attr[key])) {
+                               case 'function':
+                                       elem.addEventListener(key, attr[key]);
+                                       break;
+
+                               case 'object':
+                                       elem.setAttribute(key, JSON.stringify(attr[key]));
+                                       break;
+
+                               default:
+                                       elem.setAttribute(key, attr[key]);
+                               }
 
        if (typeof(data) === 'function')
                data = data(elem);