【问题标题】:Backbone.History.fragment undefined in router event callback路由器事件回调中未定义 Backbone.History.fragment
【发布时间】:2012-09-01 01:07:01
【问题描述】:

我的代码试图跟踪 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);
    });
});

此代码按预期打印“片段 xxx”,但当我在应用程序中导航时始终打印“未定义事件处理程序的片段”。

如果我先将 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);
    });
});

有人能解释一下这里发生了什么吗?

【问题讨论】:

  • 我刚刚在我正在开发的应用程序中尝试了这个,第一个示例有效(即它正确返回了片段)。您可以为此创建一个 jsfiddle 以确保它不是特定于配置的问题吗?
  • 确认。我将尝试将其提炼成一个小样本。希望我只是在做一些菜鸟。

标签: javascript backbone.js


【解决方案1】:

这可能是 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 变量捕获 answers 显示了其他方法来执行此操作。

【讨论】:

    猜你喜欢
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    相关资源
    最近更新 更多