4

Backbone js アプリケーションで現在のフラグメントを追跡しようとするコードがあります。

$(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);
    });
});

このコードは、期待どおりに「fragment xxx」を出力しますが、アプリ内を移動すると、常に「fragment from event handler undefined」を出力します。

最初に Backbone.History をローカル変数にコピーすると、次のように動作します。

$(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);
    });
});

誰かがここで何が起こっているのか説明できますか?

4

1 に答える 1

0

これは JavaScript 変数のキャプチャの問題でしょうか? たとえば、ヘルプのようなことを行います:

$(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);
});

他の JavaScript 変数キャプチャの回答のいくつかは、これを行う他の方法を示しています。

于 2012-09-07T14:10:15.850 に答える