Search code examples
javascriptjqueryurlbackbone.jsrequirejs

Backbone add ? after page url when an error occurred


I am experiencing a strange error when I run my code. I am using an application with Backbone.js and RequireJS. The problem arises when there is an error in the code (any), seems that a backbone or jquery redirect to the url existing adding a question mark ? at the end of the page name:

URL before the error: http://localhost/home#users
URL after the error : http://localhost/home?#users

This causes the page to refresh. Anyone know why this behavior?

This is my code:

  var myView = Backbone.View.extend({
    events: { 
            'click button#lookUp':'lookUp'

        },
    lookUp: function(){
      //Force error to show the error calling a function does not exist
      this.triggerSomeError();
    }
  });

Router:

var navigate = function(url) {
    appRouter.navigate(url, {
      trigger: true
    });
}

var initialize = function(){
    appRouter = new AppRouter;
    Backbone.history.start();
}

Html:

<button class="alinear-btn btn btn-primary" id="lookUp">Imprimir</button>      

Chrome developer console:

Console log from Chrome


Solution

  • This is a pretty common error that we've run into. You need to change your code to the following:

    var myView = Backbone.View.extend({
        events: { 
            'click button#lookUp':'lookUp'
        },
    
        lookUp: function(event) {
            event.preventDefault();
    
            //Force error to show the error calling a function does not exist
            this.triggerSomeError();
        }
    });
    

    By default an event object is passed to a function called from the events collection, and you need to use this to prevent the default behavior. You can name the parameter whatever. I just typically call it event to be explicit.

    What you are actually suppressing here is the default behavior of that button in the browser, which is to do a form submit. When you do a form submit in the browser it tries to take everything that's in the form and append it on to the url as query parameters. In this case the button is not in any form and so it's basically appending nothing and just putting the question mark for the query parameters.

    The reason you got down votes and the reason you're getting an error is because you didn't create a method in your view called triggerSomeError() so of course you're going to get an error on that. However that's completely independent and has nothing to do with what's going on with your url path.