Backbone:刷新当前路由

22

我注意到主路由器的导航方法不会重新加载当前路径。

例如,当前路线是/view1,你调用router.navigate('view1',{trigger:true});。它不会再次触发路由事件。

这是我测试用的代码:

<html>
<head>
    <title>Testing123</title>
    <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
    <script src="http://underscorejs.org/underscore-min.js" type="text/javascript"></script>
    <script src="http://backbonejs.org/backbone-min.js" type="text/javascript"></script>
    <style type="text/css" media="screen">
        #box{
            width:400px;
            height:400px;
            background-color:red;
        }       
    </style>
</head>
<body>
    <button id='view1'>view1</button>
    <button id='view2'>view2</button>
    <br/>
    <div id='box'>

    </div>
    <script type="text/javascript" charset="utf-8" async defer>
        var SystemRouter = Backbone.Router.extend({

          routes: {
            "view1":"view1",
            "view2":"view2"
          },

          view1: function() {
            console.log('view1');
          },

          view2: function() {
            console.log('view2');
          }

        });

        var sys = new SystemRouter();
        Backbone.history.start({pushState: true, root: "/test/routing.html#/"});
        sys.navigate('view1');

        $('#view1').click(function(){
            sys.navigate('view1',{trigger:true});
        });

        $('#view2').click(function(){
           sys.navigate('view2',{trigger:true});
        }); 
    </script>
</body>
</html>

上面的代码将加载/view1路径,它会打印'view1'。但是如果您尝试点击按钮导航到/view1路径,它将被忽略。

我的问题是:如果路由事件与当前路径相同,我该如何调用它?

2个回答

32

有几件事情可以达到这个目的。如果您预计要导航到已经在URL中的路由,则首先使用Backbone.history.fragment检查当前路由片段,看它是否与您想要激活的路由相同。如果是,那么您可以执行下列任何操作之一:

  1. 您可以直接调用路由方法:sys.view1();

  2. 您可以将片段设置为另一个无效的路由,然后再返回到您想要的路由。

    sys.navigate('someDeadRoute'); sys.navigate('view1',{trigger: true});

  3. 您可以停止并重新启动路由器:

    Backbone.history.stop(); Backbone.history.start()

    这将重新捕捉路由并运行它。

我认为我会选择#1。


1
在我找到这个解决方案之前,我已经尝试过选项1,但是当我尝试返回时,路由更新了但视图没有更新。你遇到过这个问题吗? - coder

29

与其启动和停止Backbone的历史记录,您可以调用Backbone.history.loadUrl

要刷新当前页面:

Backbone.history.loadUrl(Backbone.history.fragment);

或用作链接处理程序:

// `Backbone.history.navigate` is sufficient for all Routers and will trigger the
// correct events. The Router's internal `navigate` method calls this anyways.
var ret = Backbone.history.navigate(href, true);

// Typically Backbone's history/router will do nothing when trying to load the same URL.
// But since we want it to re-fire the same route, we can detect 
// when Backbone.history.navigate did nothing, and force the route.
if (ret === undefined) {
    Backbone.history.loadUrl(href);
}

这种方法对我来说似乎有效,而且您不会失去状态,而通过停止和启动历史记录,您会失去状态? - Alexander Mills

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接