luci-base: ui.js: add createHandlerFn() helper
authorJo-Philipp Wich <jo@mein.io>
Wed, 14 Aug 2019 20:54:59 +0000 (22:54 +0200)
committerJo-Philipp Wich <jo@mein.io>
Wed, 14 Aug 2019 20:58:15 +0000 (22:58 +0200)
The createHandlerFn() helper function is useful to construct onclick
or similar event handling functions. It will add a "spinning" CSS
class on the event target element and disable the element, wrap the
given function with Promise.resolv() and re-enable the target element
once the promise is settled.

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

index 23a9d7bfda21592353f1acb304f6e3beb78e4d40..e00868171081f02611fb0da27b5b563d916aadef 100644 (file)
@@ -2081,6 +2081,29 @@ return L.Class.extend({
                catch (e) { }
        },
 
+       createHandlerFn: function(ctx, fn /*, ... */) {
+               if (typeof(fn) == 'string')
+                       fn = ctx[fn];
+
+               if (typeof(fn) != 'function')
+                       return null;
+
+               return Function.prototype.bind.apply(function() {
+                       var t = arguments[arguments.length - 1].target;
+
+                       t.classList.add('spinning');
+                       t.disabled = true;
+
+                       if (t.blur)
+                               t.blur();
+
+                       Promise.resolve(fn.apply(ctx, arguments)).then(function() {
+                               t.classList.remove('spinning');
+                               t.disabled = false;
+                       });
+               }, this.varargs(arguments, 2, ctx));
+       },
+
        /* Widgets */
        Textfield: UITextfield,
        Checkbox: UICheckbox,