Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-eventsbackbone-routing

Backbone: Call a function of the view when back button of browser is clicked


I want to call function deleteMarker of my current view, when back button of the browser is clicked. I've searched for similar questions but none could help me.

Current View that I want call function deleteMarker when back button is clicked:

ev.views.Evento = Backbone.View.extend({
    map: 'null',
    initialize: function(id){
      .....
    },
    // function that will call
    deleteMarker: function(){
        this.marker.remove();
    },      
    render: function(id){
        .....
    }

});

app.js

var ev = new Application();

ev.Router = Backbone.Router.extend({

    routes: {
        "": "home",
        "evento/:id" : "evento"
    }, 
    home: function(){
        setTimeout(function(){
            $('#rightcolumn').html(new ev.views.Home_Eventos(ev.shell.map).el);
        }, 0);

    },  
    evento: function(id){
        $('#rightcolumn').html(new ev.views.Evento(id).el);    
    }
});

$(document).on('ready', function() {
    ev.templateLoader.load(['shell', 'home_list_eventos', 'evento'], function () {
        ev.shell = new ev.views.Shell({el: "#shell"});
        ev.router = new ev.Router();
        Backbone.history.start();
    });
});

Solution

  • I found the solution for this to work here: Backbone.js history 'on route change' event. Here's go my solution:

    ev.router.on("route", function(route, params) {
       if(route == "home"){
          console.log("Different Page: " + route);
          that.deleteMarker();
       }
    
    });
    

    When I press the back button of browser, it will check if the route is home. If it is then fire the function or whatever you want. I hope this help you in future.