From: Jo-Philipp Wich Date: Mon, 5 Jan 2015 18:16:18 +0000 (+0100) Subject: luci2: implement Class.require() and Class.instantiate() X-Git-Url: http://git.archive.openwrt.org/?p=project%2Fluci2%2Fui.git;a=commitdiff_plain;h=863e738b445e2e53f8d84dd12535781b2d6fc081 luci2: implement Class.require() and Class.instantiate() The two functions allow dynamic loading of additional components. Signed-off-by: Jo-Philipp Wich --- diff --git a/luci2/htdocs/luci2/luci2.js b/luci2/htdocs/luci2/luci2.js index 284f880..432248c 100644 --- a/luci2/htdocs/luci2/luci2.js +++ b/luci2/htdocs/luci2/luci2.js @@ -226,6 +226,55 @@ function LuCI2() return _class; }; + Class.require = function(name) + { + var path = '/' + name.replace(/\./g, '/') + '.js'; + + return $.ajax(path, { + method: 'GET', + async: false, + cache: true, + dataType: 'text' + }).then(function(text) { + var code = '%s\n\n//@ sourceURL=%s/%s'.format(text, window.location.origin, path); + var construct = eval(code); + + var parts = name.split(/\./); + var cparent = L.Class || (L.Class = { }); + + for (var i = 1; i < parts.length - 1; i++) + { + cparent = cparent[parts[i]]; + + if (!cparent) + throw "Missing parent class"; + } + + cparent[parts[i]] = construct; + }); + }; + + Class.instantiate = function(name) + { + Class.require(name).then(function() { + var parts = name.split(/\./); + var iparent = L; + var construct = L.Class; + + for (var i = 1; i < parts.length - 1; i++) + { + iparent = iparent[parts[i]]; + construct = construct[parts[i]]; + + if (!iparent) + throw "Missing parent class"; + } + + if (construct[parts[i]]) + iparent[parts[i]] = new construct[parts[i]](); + }); + }; + this.defaults = function(obj, def) { for (var key in def)