Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自定义事件 #70

Open
gdutwyg opened this issue Sep 17, 2019 · 2 comments
Open

自定义事件 #70

gdutwyg opened this issue Sep 17, 2019 · 2 comments
Labels

Comments

@gdutwyg
Copy link
Owner

gdutwyg commented Sep 17, 2019

开头

今天在群里看到有妹子提出一个问题,vue-router hash模式路由变化无法触发hashchange事件,应该怎么处理?

答: 其实是因为vue-router内部是用 replaceState/pushState 触发hash的变化,而replaceState和pushState的调用并不会触发hashchange事件或者popstate事件。

ps: hashchange事件需要挂载在window才能触发

思绪良久,苦无破敌之计,谷歌一下,发现有大佬用自定义事件可以解决,因为无法触发,只能在replaceState/pushState的调用时添加自定义事件,通过自定义事件去触发。

Event

构造函数Event

语法

 const event = new Event(typeArg, eventInit);
  • typeArg string类型,表示所创建事件的名称
  • eventInit object类型,可选
    "bubbles",可选,Boolean类型,默认值为 false,表示该事件是否冒泡。
    "cancelable",可选,Boolean类型,默认值为 false, 表示该事件能否被取消。
    "composed",可选,Boolean类型,默认值为 false,指示事件是否会在影子DOM

dispatchEvent

触发自定义事件

// 创建一个支持冒泡且不能被取消的look事件
var ev = new Event("look", {"bubbles":true, "cancelable":false});
document.dispatchEvent(ev)

// 事件可以在任何元素触发,不仅仅是document
myDiv.dispatchEvent(ev)

自定义事件

// 往pushState里添加自定义事件
function newEvent (type) {
  const fn= history[type]
  return function () {
      const returnValue = fn.apply(this, arguments)
      const e = new Event(type)
      e.arguments = arguments
      // 触发自定义事件
      window.dispatchEvent(e)
      return returnValue 
  }
}
history.pushState = newEvent('pushState')
history.replaceState= newEvent('replaceState')
// 监听自定义事件
window.addEventListener('pushState', function (e) {
  console.log('pushState')
})
window.addEventListener('replaceState', function (e) {
  console.log('replaceState')
})

参考

在单页应用中,如何优雅的监听url的变化
Event

@gdutwyg gdutwyg added the js label Sep 17, 2019
@gdutwyg gdutwyg added the Vue label Nov 4, 2019
@nbutmickey
Copy link

你好,我想知道这一段代码的含义是啥?
const returnValue = fn.apply(this, arguments)

@gdutwyg
Copy link
Owner Author

gdutwyg commented Feb 10, 2020

你好,我想知道这一段代码的含义是啥?
const returnValue = fn.apply(this, arguments)

执行history[type]这个函数(也就是fn),有返回值就返回

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants