on.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. var _ = require('../../util')
  2. var keyCodes = {
  3. esc: 27,
  4. tab: 9,
  5. enter: 13,
  6. space: 32,
  7. 'delete': 46,
  8. up: 38,
  9. left: 37,
  10. right: 39,
  11. down: 40
  12. }
  13. /**
  14. * Wrap a handler function so that it only gets triggered on
  15. * specified keypress events.
  16. *
  17. * @param {Function} handler
  18. * @param {String|Number} key
  19. * @return {Function}
  20. */
  21. function keyFilter (handler, key) {
  22. var code = keyCodes[key]
  23. if (!code) {
  24. code = parseInt(key, 10)
  25. }
  26. return function (e) {
  27. if (e.keyCode === code) {
  28. return handler.call(this, e)
  29. }
  30. }
  31. }
  32. module.exports = {
  33. acceptStatement: true,
  34. priority: 700,
  35. bind: function () {
  36. // 1.0.0 key filter
  37. var rawEvent = this.event = this.arg
  38. var keyIndex = rawEvent.indexOf('.')
  39. if (keyIndex > -1) {
  40. this.event = rawEvent.slice(0, keyIndex)
  41. this.key = rawEvent.slice(keyIndex + 1)
  42. }
  43. // deal with iframes
  44. if (
  45. this.el.tagName === 'IFRAME' &&
  46. this.event !== 'load'
  47. ) {
  48. var self = this
  49. this.iframeBind = function () {
  50. _.on(self.el.contentWindow, self.event, self.handler)
  51. }
  52. this.on('load', this.iframeBind)
  53. }
  54. },
  55. update: function (handler) {
  56. if (typeof handler !== 'function') {
  57. process.env.NODE_ENV !== 'production' && _.warn(
  58. 'on-"' + this.event + '="' +
  59. this.expression + '" expects a function value, ' +
  60. 'got ' + handler
  61. )
  62. return
  63. }
  64. if (this.key) {
  65. handler = keyFilter(handler, this.key)
  66. }
  67. this.reset()
  68. var scope = this._scope || this.vm
  69. this.handler = function (e) {
  70. scope.$event = e
  71. var res = handler(e)
  72. scope.$event = null
  73. return res
  74. }
  75. if (this.iframeBind) {
  76. this.iframeBind()
  77. } else {
  78. _.on(this.el, this.event, this.handler)
  79. }
  80. },
  81. reset: function () {
  82. var el = this.iframeBind
  83. ? this.el.contentWindow
  84. : this.el
  85. if (this.handler) {
  86. _.off(el, this.event, this.handler)
  87. }
  88. },
  89. unbind: function () {
  90. this.reset()
  91. }
  92. }