notify.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var Emitter = require('./Emitter');
  2. var root = require('./root');
  3. var each = require('./each');
  4. var Notification = root.Notification;
  5. exports = function(title, options) {
  6. var notification = new exports.Notification(title, options);
  7. notification.show();
  8. };
  9. exports.Notification = Emitter.extend({
  10. initialize: function Notification(title) {
  11. var options =
  12. arguments.length > 1 && arguments[1] !== undefined
  13. ? arguments[1]
  14. : {};
  15. this._options = options;
  16. this._title = title;
  17. this.callSuper(Emitter, 'initialize', arguments);
  18. },
  19. handleEvent: function(e) {
  20. this.emit(e.type, e);
  21. },
  22. show: function() {
  23. var _this = this;
  24. if (!Notification) {
  25. return this.emit('error', Error('Notification is not supported'));
  26. }
  27. if (Notification.permission === 'granted') {
  28. this._show();
  29. } else {
  30. Notification.requestPermission(function(permission) {
  31. switch (permission) {
  32. case 'granted':
  33. _this._show();
  34. break;
  35. case 'denied':
  36. _this.emit(
  37. 'error',
  38. Error('Notification permission is denied')
  39. );
  40. break;
  41. }
  42. });
  43. }
  44. },
  45. _show: function() {
  46. var _this2 = this;
  47. var notification = new Notification(this._title, this._options);
  48. each(['show', 'close', 'click'], function(type) {
  49. notification.addEventListener(type, _this2, false);
  50. });
  51. }
  52. });
  53. module.exports = exports;