Search code examples
javascriptjquerybackbone.js

Cannot route across the Backbone views


I am developing a blog app with fiddle here for self teaching. I am facing with problems and gradually overcoming them.

I currently managed to render my initial view. Bur I want another view to populate the body entirely. From the first view to that second view and later to others I try to go with anchors preventedDefault and trigger the event method in the current view that hits a Backbone router route. And from there to the router method to construct my second view finally.

Up to now I get the error on js console:

[Error] TypeError: undefined is not a function (evaluating 'Backbone.navigate( this.hrefOfPostForm , {trigger: true})')
toPostFormRoute (app.js, line 45)
(anonymous function) ([native code], line 0)
dispatch (jquery.min.js, line 3)
handle (jquery.min.js, line 3)

What can be the problem be with my navigation code?


Solution

  • First off, Backbone.navigate doesn't exist. Backbone.history.navigate does. But you still have another issue.

    Check out the Backbone.Router.navigate API: the first argument is the route you want to re-route to, NOT the function you want it to hit. This is what you are trying to do:

    var sampleA = function(){};
    
    Backbone.history.navigate(sampleRouteA, {trigger: true});
    

    This will not work. You need to define the router handler, then navigate to the specified route, which Backbone will handle. The following will (probably) work:

    var sampleA = function(){};
    
    var someRoutes = Backbone.Router.extend({
      routes: {
        'sampleRoute/A': 'doSampleA',
        'sampleRoute/B': 'doSampleB'
      },
    
      'doSampleA': function(){
        sampleA();
      },
    
      'doSampleB': function(){
      },
    });
    
    Backbone.history.navigate('sampleRoute/A', {trigger: true});
    

    Here is the corresponding jsFiddle. Open your devtools (F12 on Chrome), and watch the log as you type in an id and click the button. The url of the iframe will change to match the route, along with the id you provide. This is how Backbone routing should work.