Search code examples
javascriptbackbone.jsbackbone-eventsbackbone-routing

How to prevent routing in Backbone.js?


When I click 'Cancel' from First page - it's ok. But 'Cancel' doesn't work when I move to 'Second page'. In this case router redirects application to "" route. I need to prevent this redirection.

"Cancel" - hide links, "Second page" - move to Second page

<script type="text/html" id="template">
    <a href="#" class="cancel">Cancel</a>
    <a href="#second">Second page</a>
</script>

<div id="container"></div>    

<script>
var View = Backbone.View.extend({

    template: $('#template').html(),

    events: {
        "click .cancel": "cancel"
    },

    cancel: function () {
        this.$el.hide();
    },

    render: function () {
        this.$el.html(this.template);
        return this;
    }
});

var AppRouter = Backbone.Router.extend({

    routes: {
        "": "first",
        "second": "second"
    },

Create view and replace container's html

    links: function () {
        var view = new View;
        $('#container').html(view.render().el);
    },

    second: function () {
        this.links();
        $('#container').prepend("<h1>Second page</h1>");
    },

    first: function () {
        this.links();
        $('#container').prepend("<h1>First page</h1>");
    }

});

$(document).ready(function () {
    app = new AppRouter;
    Backbone.history.start();
});
</script>

Solution

  • I think you should return false from the cancel handler to prevent navigation to #:

    cancel: function (e) {
            this.$el.hide();
            return false;
        },
    

    http://api.jquery.com/on/ says:

    Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault().