0

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();
    });
});
seal
  • 520
  • 2
  • 5
  • 20
  • In ev.Router.home, why are you calling `setTimeout` with a milliseconds parameter of 0? It seems to me that this defeats the point of `setTimeout`. – 76484 Dec 23 '14 at 02:12
  • I searched and found some interesting discussions of this pattern: http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – 76484 Dec 23 '14 at 02:53
  • http://stackoverflow.com/questions/14543245/browser-back-button-handling http://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser Just listen to the event in `Router` and trigger a Backbone event, which the view might be listening to do it's job. – coding_idiot Dec 23 '14 at 10:13

2 Answers2

0

I would use .onpopstate function filtering the event, checking is history.back() has been triggered. I'm not sure what object is passed to the callback so check how "event" is structured filter is adequately.

window.onpopstate = function(event) {
  if(event == "Backbone.history.back()") triggersomething();
};

Let me know if it works. Hope it helps.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
François Richard
  • 6,817
  • 10
  • 43
  • 78
0

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.

Community
  • 1
  • 1
seal
  • 520
  • 2
  • 5
  • 20
  • You can make this even prettier by removing the `if` control and subscribing to the "route:home" event. – 76484 Dec 24 '14 at 06:53