javascript - 如何在backbone.js事件委托(delegate)中使用 "hashchange"事件?

标签 javascript events backbone.js hashchange

在我的backbone.js项目中,我需要一个仅在window.location.hash更改时触发的方法。我为我的问题找到了一些替代解决方案 here .

此外,我可以通过在主干 View 初始化函数中创建一个事件来解决这个问题,如下所示

Backbone.View.extend({   
  initialize() {
      $(window).on('hashchange',()=> {
            console.log('yes hashchange events works')
      });
  }

但我寻求一种使用 backbone.js eventDelegateslistenTo

的解决方案

提前致谢

最佳答案

您可以为此范围使用Backbone.history

History serves as a global router (per frame) to handle hashchange events or pushState, match the appropriate route, and trigger callbacks. You shouldn't ever have to create one of these yourself since Backbone.history already contains one.

因为它会触发回调,所以您可以监听 hashchange 事件:

Backbone.history.on("all", function (route, router) {
    console.log(window.location.hash);
});

Backbone.history.on("route", function () {
    console.log(window.location.hash);
});

关于javascript - 如何在backbone.js事件委托(delegate)中使用 "hashchange"事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37023773/

相关文章:

javascript - 下面的 javascript 片段有什么不同吗?

Backbone.js 和导航

javascript - 使用replaceWith()将一个按钮替换为另一个按钮

javascript - “滚动”事件未在 CompositeView 中触发

javascript - 将方括号拆分为逗号,删除第一个和最后一个逗号

javascript - 如何使用 tailwind 在聚焦时将边框应用于 div 元素?

c - 如何在循环中等待两种类型的事件(C)?

来自父类的Angular2 EventEmitter

javascript - 目标转换问题 - var 修改

javascript - 为什么 Chrome 不允许 Web Worker 在 JavaScript 中运行?