processTriggerEvent.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. function createCustomEvent(props = {}) {
  2. const e = {
  3. target: {
  4. dataset: {},
  5. },
  6. currentTarget: {
  7. dataset: {},
  8. // 组件的id
  9. id: props.id,
  10. },
  11. }
  12. Object.keys(props)
  13. .forEach((prop) => {
  14. if (prop.match(/^data-/)) {
  15. const originProp = prop
  16. prop = prop.replace(/[A-Z]/g, ($) => {
  17. return $.toLowerCase()
  18. })
  19. prop = prop.split('-')
  20. prop.shift()
  21. prop = prop.join('')
  22. e.target.dataset[prop] = props[originProp]
  23. e.currentTarget.dataset[prop] = props[originProp]
  24. }
  25. })
  26. return e
  27. }
  28. function processTriggerEvent() {
  29. this.triggerEvent = function(event, data) {
  30. const eventType = (event[0].toLowerCase() + event.substring(1))
  31. event = `on${event[0].toUpperCase()}${event.substring(1)}`
  32. const e = createCustomEvent(this.props)
  33. e.type = eventType
  34. e.detail = data
  35. event = event.replace(/-\w+/, (name) => {
  36. name = name[1].toUpperCase() + name.substring(2)
  37. return name
  38. })
  39. if (typeof this.props[event] === 'function') {
  40. this.props[event](e)
  41. }
  42. }
  43. }
  44. module.exports = processTriggerEvent