3

I need to know when a UIKit notification has been closed.

The UIkit notification plugin (https://getuikit.com/docs/notification) mentions that it has a close event. Is it possible to use this for instances triggered programatically?

e.g.

UIkit.notification({
    message: 'my-message!',
    status: 'primary',
    timeout: null
});
UIKit.o

I've tried putting the nofication on a variable, (as suggested https://getuikit.com/docs/javascript#programmatic-use, where it even states You'll receive the initialized component as return value - but you don't)

let foo = UIkit.notification('message'); // foo is undefined

I've tried chaining the on method

UIkit.notification.on('close', function() { ... }); // on is undefined

but the .on method is part of UIkit.util.on($el, event, fn) and there is no $el when calling notification programatically.

The only other way I can think of doing it is putting a mutation observer onto the body and watching to the notification element to change state, but this seems like overkill.

frumbert
  • 2,323
  • 5
  • 30
  • 61

3 Answers3

3

You can store a handle to the notification...

warning_notification = UIkit.notification({message: 'Warning message...',
                                           status: 'warning', timeout: 1000});

... and check if this is the origin of the close event:

UIkit.util.on(document, 'close', function(evt) {
  if (evt.detail[0] === warning_notification) {
    alert('Warning notification closed');
  }
});

Now, you will only see the alert when exactly this notification was closed.

Check out this demo.

Tom Pohl
  • 2,711
  • 3
  • 27
  • 34
2

You could try this instead

UIkit.util.on(document, 'close', function() { alert('Notification closed'); });

See this Pen

1

A bit Hacky, but the following seems to "work" :

function notify(){
  var params = Array.prototype.slice.call(arguments);
  new_f = params.shift()
  foo = UIkit.notification.apply(this, params);
  return function(foo, new_f, old_f){
    foo.close = function(){new_f(); foo.close = old_f; old_f.apply(this, arguments); }
    return foo
  }(foo, new_f, foo.close);
}

notify(function(){alert('ok');}, 'message');
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.9/js/uikit.js"></script>
hl037_
  • 3,520
  • 1
  • 27
  • 58
  • This looks better than what I ended up with. Hacky is sometimes necessary when working with libraries; chaining the function reminds me of the old days of body onload chains! – frumbert Jul 26 '18 at 02:10
  • It's "Hacky" because it is undocumented ;) ...And so, it might break on libray updates :/ I have the same need for a close trigger, and I saw this "close" attribute. Btw, if you don't do the `foo.close = old_f` part, then the event is triggered several times – hl037_ Jul 26 '18 at 09:21