Backbone.History.fragment undefined in router event callback

I have code that is trying to track the current fragment in a Backbone js application.

$(function(){ Backbone.history.start({pushState: true}); console.log("fragment " + Backbone.history.fragment); // Beef is a global that holds my router (created elsewhere) Beef.router.bind("all", function(route) { console.log("fragment from event handler " + Backbone.history.fragment); }); }); 

This code prints the "snippet xxx" as expected, but always prints the "snippet from the undefined event handler" when I navigate in the application.

If I copy Backbone.History to a local var, it works first:

 $(function(){ Backbone.history.start({pushState: true}); console.log("fragment " + Backbone.history.fragment); var hist = Backbone.history; Beef.router.bind("all", function(route) { console.log("fragment from event handler " + hist.fragment); }); }); 

Can someone explain what is going on here?

+4
source share
1 answer

Could this be a javascript variable capture problem? For example, doing something like help:

 $(function(){ Backbone.history.start({pushState: true}); console.log("fragment " + Backbone.history.fragment); (function(hist) { Beef.router.bind("all", function(route) { console.log("fragment from event handler " + hist.fragment); }); })(Backbone.history); }); 

Some of the other javascript variable captures show other ways to do this.

0
source

Source: https://habr.com/ru/post/1432878/


All Articles