Search code examples
javascripteventsbackbone.jshashchange

How to use "hashchange" event in backbone.js event delegates?


In my backbone.js project, I need a method which triggered only when window.location.hash change. I found some alternative solution for my problem as here.

Also, I can solve this problem by creating a event in my backbone view initialize function as below

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

But I seek for a solution which uses backbone.js's eventDelegates or listenTo

Thanks in advance


Solution

  • You can use Backbone.history for this scope.

    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.

    Because it triggers a callback, you can listen for hashchange events:

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

    or

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