2011-11-14 81 views
6

我有一些导航链接在应用程序启动时,我希望通过骨干(这是一个非常静态的文本内容版本,骨干应用程序底层版本)进行增强劫持。骨干路由器不会触发事件

的HTML如下:

... 
<body> 
<header> 
<nav> 
<ol> 
<li> 
<a href="/en/home">home</a> 
</li> 
<li> 
... few more links 
</header> 

然后,我的应用程序使用实例:

var App = (function(fw){ 
var $  = fw; 
var workspace   = {}; 
var self  = {}; 
var lang  = "en"; 
var models  = {...}; 
var views  = {...}; 
var collections = {...}; 
self.init = function() { 
    workspace = new Workspace(
    { 
    routes: { 
    "/": "home", 
    "/home": "home", 
    "/terms": "terms", 
    "/news": "blog" 
    }, 
    lang : lang 
    }) 
} 
return self; 
}); 
var app; 
// launch 
$(document).ready(function() { 
app = new App(jQuery); 
app.init(); 
}); 

工作区只是一个路由器,并从应用程序的路由正确通过加工成路由器初始化函数,链接也工作并按预期更改URL,并使用旧版浏览器上的哈希值进行更改。问题是路由器/工作区本身没有回调。它只是静音和犯规火的功能,当点击由

这是我的工作区/路由器:

var Workspace = Backbone.Router.extend({ 

routes : {}, 
//functions      <------------THESE 
home: function(e){ 
    e.preventDefault(); 
    console.log("home here"); 
    App.views.HomeView.render(); 
}, 
terms: function(){   //<-----------NEVER 
    console.log("terms here"); 
    App.views.TermsView.render(); 
}, 
blog: function(){   //<-----------FIRE 
    console.log("blog here"); 
}, 
initialize: function(params){ 
    var t = this; 
    var tmpr = {}; 
    for(var i in params.routes) 
    { 
    //this just fuses lang and each route so /home becomes /en/home 
        tmpr["/"+params.lang+i] = params.routes[i]; 
    } 
    this.routes = tmpr; // this is fine and when logged it shows nicely with all routes looking good 
    // router will only ever initialize once so lets deal with the stuff currently on the DOM before the app is inited. 
    $("a",$("header")).click(function(e){ 
    e.preventDefault(); 
    Backbone.history.navigate($(this).attr("href"),true);//<-- true is set? should fire methods? 
    // I've also tried all kinds of variations like t.navigate(..) where t is this workspace 
    }); 
//this also seems to be fine and either does hashes or states 
    if(history && history.pushState) { 
    Backbone.history.start({ 
    pushState : true 
    }); 
    console.log("has pushstate"); 
    } else { 
    Backbone.history.start(); 
    console.log("no pushstate"); 
    } 
    console.log("Router inited with routes:",this.routes);//logs routes nicely 
} 
}); 

回答

2

的路线运行的initialize功能时,已经被绑定(见the backbone source)。

可以触发与_bindRoutes功能结合的路线:

this.routes = tmpr; 
this._bindRoutes();