主干:单击浏览器的后退按钮时调用视图的函数

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

本文关键字:调用 视图 函数 按钮 单击 浏览器 主干      更新时间:2023-09-26

我想在单击浏览器的后退按钮时调用当前视图的函数deleteMarker。我搜索过类似的问题,但没有一个可以帮助我。

单击后退按钮时,我想调用函数deleteMarker的当前视图:

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

应用.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();
    });
});

我在这里找到了解决方案:骨干网.js历史"路线更改"事件。这是我的解决方案:

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

当我按下浏览器的后退按钮时,它会检查路线是否回家。如果是,则触发函数或任何您想要的内容。我希望这对您将来有所帮助。

我会使用 .onpopstate 函数过滤事件,检查是否已触发 history.back((。我不确定将什么对象传递给回调,因此请检查"事件"如何结构化过滤器是否足够。

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

让我知道它是否有效。希望对您有所帮助。