4

I have code that is attempting to keep track of 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 'fragment xxx ' as expected but always prints 'fragment from event handler undefined' when I navigate in the app.

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

$(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 whats going on here?

David Tinker
  • 9,383
  • 9
  • 66
  • 98
  • 1
    I just tried this in an app I'm working on and the first example works (i.e. it correctly returns the fragment). Can you create a jsfiddle for this to make sure it's not a configuration-specific issue? – Chris Salzberg Sep 07 '12 at 07:13
  • Ack. I will try to distil this down into a small sample. Was hoping I was just doing something noob. – David Tinker Sep 07 '12 at 09:12

1 Answers1

0

Could this be a javascript variable capture issue? For instance, does do 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 capture answers show other ways to do this.

Community
  • 1
  • 1
River
  • 1,504
  • 13
  • 21