The trunk router will not fire events

I have some dom navigation links when the application is running, which I want to capture for progressive improvement through Backbone (this is a very static version of the text content that underlies the base application).

html looks like this:

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

Then my application is created using:

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

The workspace is just a router, and these routes from the application are correctly processed in the router using the initialization function, and the links also work and change the URL as expected, and they do this using hashes in older browsers. The problem is that no callbacks occur in the Router / Workspace itself. It simply mutes the sound and does not launch the function when clicks are clicked.

Here is my workspace / router:

 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 } }); 
+6
source share
1 answer

Routes were already connected when executing the initialize function (see the source of the backbone network ).

You can activate route binding using the _bindRoutes function:

 this.routes = tmpr; this._bindRoutes(); 
+2
source

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


All Articles